import 'dart:convert';

import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:flyinsono/managers/interfaces/report_template.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/remedical/consultation/state.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_images_list_view.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_images_view.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/fcustom_flat_button.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/report_preview.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/reports_mobile.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/write_report.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controller.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/models.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/widgets/mobile/record_patient_refer_mobile.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:fis_lib_report/report/report_template_document.dart';
import 'package:fis_lib_report/report_info/report_info.dart' as report;
import 'package:fis_lib_report/report_info/input_text_info.dart';
import 'package:fis_lib_report/report_info/element_info.dart';
import 'package:fis_lib_report/report_info/single_selected_info.dart';
import 'package:fis_lib_report/report_info/element_tag_names.dart';
import 'package:fis_lib_report/report_info/input_image_list_info.dart';

class RecordCard extends FStatefulWidget implements FPage {
  ///检查记录信息
  final ConsultationsRecordData recordInfo;
  final void Function() onTapDetail;

  RecordCard(this.recordInfo, this.onTapDetail);

  @override
  FState<FStatefulWidget> createState() {
    return RecordCasrdState();
  }

  @override
  String get pageName => "RecordCasrd";
}

class RecordCasrdState extends FState<RecordCard> {
  final double _cardHeight = i18nBook.isCurrentRussian ? 217 : 183;
  //标题与内容间隔
  final double _sizeBetween = i18nBook.isCurrentRussian ? 10 : 15;
  final remedicalManager = Get.find<IRemedicalManager>();
  final reportManager = Get.find<IReportManager>();
  List<String> _selectedRemedicalImages = [];
  String get recordCode => widget.recordInfo.recordCode!;

  ///超声机描述
  final TextEditingController _desController = TextEditingController();

  ///超声机提示
  final TextEditingController _consualationController = TextEditingController();
  final FEventHandler<List<String>> _onSelectedImages =
      FEventHandler<List<String>>();
  List<ReportDTO> _reportList = [];
  final _onReportsChange = FEventHandler<List<ReportDTO>>();
  final _onCreatePermissionChange = FEventHandler<bool>();
  String _gender = '';
  String _specie = '';

  ///按钮间分割线高度
  static const double _buttonSplitLineHeight = 25;

  ///姓名文字样式
  final TextStyle _nameTextStyle = TextStyle(
    fontSize: FFontSizes.H3,
    color: Colors.black87,
    overflow: TextOverflow.ellipsis, // 设置省略方式
  );
  final decoration = BoxDecoration(
    boxShadow: [
      BoxShadow(
        color: Colors.grey[300]!,
        offset: Offset(2.0, 2.0), //阴影xy轴偏移量
        blurRadius: 5.0, //阴影模糊程度
        spreadRadius: 2.0, //阴影扩散程度
      )
    ],
    borderRadius: BorderRadius.all(
      Radius.circular(8),
    ),
    color: Colors.white,
  );

  @override
  void initState() {
    reportManager.onEditReport.addListener(onEditReport);
    super.initState();
  }

  @override
  void dispose() {
    reportManager.onEditReport.removeListener(onEditReport);
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      decoration: decoration,
      margin: EdgeInsets.only(left: 7, right: 7, top: 10),
      padding: EdgeInsets.all(7),
      height: _cardHeight,
      child: FColumn(
        children: [
          _buildRecordInfoView(),
          const FSizedBox(height: 5),
          FDivider(
            height: 1,
            thickness: 1,
            color: Colors.grey[200],
          ),
          _buildOperateButtons(),
        ],
      ),
    );
  }

  FWidget _buildRecordInfoView() {
    return FExpanded(
      child: FColumn(
        children: [
          _buildPatientNameAndStatus(),
          if (i18nBook.isCurrentRussian) ...[
            _buildStatus(),
          ],
          const FSizedBox(height: FSpacings.M),
          FRow(
            children: [
              FExpanded(
                child: _buildAgeInfo(widget.recordInfo.age), //年龄
              ),
              FExpanded(
                child: _buildGenderInfo(widget.recordInfo.sex), //性别
              ),
            ],
          ),
          const FSizedBox(height: FSpacings.M),
          _buildDeviceHospitalName(),
          const FSizedBox(height: FSpacings.M),
          _buildTime(widget.recordInfo.createTime),
        ],
      ),
    );
  }

  FWidget _buildDeviceHospitalName() {
    var name = widget.recordInfo.rootOrganizationName;
    return FRow(
      children: [
        const FSizedBox(width: FSpacings.M),
        FTitleField(
          i18nBook.organization.orgName.t,
          FText(
            name.isNullOrEmpty ? i18nBook.remedical.notFill.t : name!,
            style: TextStyle(color: Colors.black87),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          minTitleWidth: 90,
          maxLargeFieldWidth: MediaQuery.of(context).size.width - 155,
          sizeBetween: _sizeBetween,
          isBold: false,
        ),
      ],
    );
  }

  FWidget _buildOperateButtons() {
    return FSizedBox(
      height: 38,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          FCustomFlatButton(
            i18nBook.common.image.t,
            onTapImage,
            businessParent: widget,
            fontColor: FTheme.ins.colorScheme.primary,
          ),
          _getButtonSplitLine(),
          FCustomFlatButton(
            i18nBook.common.report.t,
            routerToReportsPage,
            businessParent: widget,
            fontColor: FTheme.ins.colorScheme.primary,
          ),
          _getButtonSplitLine(),
          if (widget.recordInfo.rootOrganizationCode ==
                  Store.user.rootOrganizationCode ||
              widget.recordInfo.referralType ==
                  ReferralTypeEnum.ReferralIn) ...[
            FCustomFlatButton(
              i18nBook.remedical.transfer.t,
              () async {
                await Get.to(
                  RecordPatientReferMobile(
                    patientName: widget.recordInfo.patientName ?? '',
                    recordCode: widget.recordInfo.recordCode,
                    isShowApplay: ![
                      ReferralTypeEnum.ReferralIn,
                      ReferralTypeEnum.ReferralOut
                    ].contains(widget.recordInfo.referralType),
                    referralType: widget.recordInfo.referralType,
                  ),
                );
                final controller = Get.find<ConsultationRecordViewController>();
                controller.subjectMatter = '';
                controller.referUserList = [];
                controller.referralOrganizationCode = null;
                controller.referralUserCode = null;
              },
              businessParent: widget,
              fontColor: FTheme.ins.colorScheme.primary,
            ),
            _getButtonSplitLine(),
          ],
          FCustomFlatButton(
            i18nBook.notification.detail.t,
            widget.onTapDetail,
            businessParent: widget,
            fontColor: FTheme.ins.colorScheme.primary,
          ),
        ],
      ),
    );
  }

  ///按钮间分割线
  FWidget _getButtonSplitLine() {
    return FContainer(
      height: _buttonSplitLineHeight,
      child: FVerticalDivider(
        width: 1,
        thickness: 1,
        color: FTheme.ins.colorScheme.line,
      ),
    );
  }

  ///性别
  FWidget _buildGenderInfo(String? sex) {
    var gender = sex ?? '';
    return FRow(children: [
      const FSizedBox(width: FSpacings.M),
      FTitleField(
        i18nBook.remedical.gender.t,
        sizeBetween: _sizeBetween,
        minTitleWidth: i18nBook.isCurrentChinese
            ? 88
            : (i18nBook.isCurrentEnglish || i18nBook.isCurrentSpanish)
                ? 48
                : 60,
        FText(
          gender.isEmpty ? i18nBook.remedical.notFill.t : gender,
        ),
        isBold: false,
      ),
    ]);
  }

  //年龄
  FWidget _buildAgeInfo(String? patientAge) {
    var age = patientAge ?? '';
    return FRow(
      children: [
        const FSizedBox(width: FSpacings.M),
        FTitleField(
          i18nBook.remedical.age.t,
          FText(
            age.isEmpty ? i18nBook.remedical.notFill.t : age,
            style: TextStyle(color: Colors.black87),
          ),
          minTitleWidth: i18nBook.isCurrentChinese
              ? 88
              : (i18nBook.isCurrentEnglish || i18nBook.isCurrentSpanish)
                  ? 48
                  : 60,
          sizeBetween: _sizeBetween,
          isBold: false,
        ),
      ],
    );
  }

  FWidget _buildPatientNameAndStatus() {
    var recordStatus = widget.recordInfo.recordStatus;
    var referralType = widget.recordInfo.referralType;
    String label = '';
    if (referralType == ReferralTypeEnum.ReferralIn) {
      label += '(${i18nBook.remedical.transferiIn.t})';
    } else if (referralType == ReferralTypeEnum.ReferralOut) {
      label += '(${i18nBook.remedical.transferOut.t})';
    }
    return FRow(
      children: [
        const FSizedBox(width: FSpacings.M),
        FContainer(
          constraints: BoxConstraints(
            maxWidth: i18nBook.isCurrentRussian
                ? MediaQuery.of(context).size.width - 44
                : MediaQuery.of(context).size.width / 2 - 40, // 设置最大宽度
          ),
          child: FText(
            widget.recordInfo.patientName ?? i18nBook.remedical.notFill.t,
            style: _nameTextStyle,
            maxLines: 1,
          ),
        ),
        const FExpanded(child: FSizedBox()),
        if (!i18nBook.isCurrentRussian)
          FText(
            _stateLabel(recordStatus) + label,
            style: _getTextStyleByState(recordStatus),
          ),
        const FSizedBox(width: FSpacings.M),
      ],
    );
  }

  /// 状态文案
  String _stateLabel(RecordStatusEnum? statusEnum) {
    switch (statusEnum) {
      case RecordStatusEnum.Completed:
        return i18nBook.remedical.reported4Label.t;
      case RecordStatusEnum.NotReport:
        return i18nBook.remedical.scanned4Label.t;
      case RecordStatusEnum.NotScanned:
        return i18nBook.remedical.toScan4Label.t;
      case RecordStatusEnum.Uploaded:
        return i18nBook.remedical.imageUploaded4Label.t;
      default:
        return i18nBook.remedical.notFinished4Label.t;
    }
  }

  ///获取状态文本显示样式
  TextStyle _getTextStyleByState(RecordStatusEnum state) {
    var color = Color.fromRGBO(124, 182, 90, 1);
    if ([RecordStatusEnum.NotReport, RecordStatusEnum.NotScanned]
        .contains(state)) {
      color = Color.fromRGBO(240, 141, 46, 1);
    }
    return TextStyle(
      color: color,
      fontSize: FFontSizes.H5,
      fontWeight: FontWeight.bold,
    );
  }

  FWidget _buildTime(DateTime? createTime) {
    return FRow(children: [
      const FSizedBox(width: FSpacings.M),
      FTitleField(
        i18nBook.common.createTime.t,
        sizeBetween: _sizeBetween,
        minTitleWidth: 90,
        FText(
          DateFormat("yyy-MM-dd HH:mm:ss").format(
            createTime?.toLocal() ?? DateTime.now(),
          ),
          style: TextStyle(color: Colors.black87),
        ),
        isBold: false,
      ),
    ]);
  }

//------------------------------点击事件处理----------------------------

  ///报告列表
  Future<void> routerToReportsPage({bool isLandscapeMode = false}) async {
    _reportList = await remedicalManager.findExamReports(recordCode);
    var patientInfoDto = await remedicalManager
        .findPatientByCode(widget.recordInfo.patientCode!);
    var patientInfo = remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
    bool isCanWriteReport = widget.recordInfo.isCanCreateReport;
    if (_reportList.isEmpty && isCanWriteReport) {
      editReport(resizeFactor: true, isNew: true);
      return;
    }
    var mobileReportsContentView = MobileReportsContentView(
      reportList: _reportList,
      recordCode: recordCode,
      onRefresh: () async {
        _reportList = await remedicalManager.findExamReports(recordCode);
        return _reportList;
      },
      patientInfo: patientInfo,
      onReportsChange: _onReportsChange,
      onCreatePermissionChange: _onCreatePermissionChange,
      isCanWriteReport: isCanWriteReport,
      onTapCard: onTapCard,
      onTapShare: (reportCode) {},
      onEditReport: () {
        editReport(isNew: true);
      },
      isLandscapeMode: isLandscapeMode,
      onTapImage: (index) {
        openImagesPage();
      },
    );
    Get.to(() => mobileReportsContentView);
  }

  //预览报告
  Future<void> onTapCard(int index) async {
    final baseReportInfo = _reportList[index];
    var reportCode = baseReportInfo.reportCode ?? '';
    var reportInfo = await reportManager.findReportByCodeAsync(reportCode);
    final preList = reportInfo.reportPreviewList ?? [];
    if (preList.isEmpty) {
      PromptBox.toast(i18nBook.remedical.reportNoInit.t);
    } else {
      Get.to(() => ReportPreview(
            reportInfo: reportInfo,
            reportList: _reportList,
          ));
    }
  }

  ///选择图像
  Future<void> openImagesPage({bool isSelectImageModel = false}) async {
    List<RemedicalMeasuredInfoDTO> measureImages =
        await remedicalManager.findRemedicalMeasuredInfoAsync(recordCode);
    List<RemedicalAISelectedInfoDTO> aiImages = await remedicalManager
        .findAIImages(recordCode, widget.recordInfo.patientCode ?? "");
    RemedicalListResult cloudImageInfo =
        await reportManager.getRemedicalListByRecordInfoAsync(recordCode);

    if (isSelectImageModel) {
      Get.to(
        () => ExamImagesView(
          patientCode: widget.recordInfo.patientCode,
          measureImages: measureImages,
          selectedImags: _selectedRemedicalImages,
          isSingle: true,
          isSelectImageModel: true,
          cloudImageInfos: [cloudImageInfo],
          onSubmit: (List<String> v) {
            setState(() {
              _selectedRemedicalImages = v;
            });
            _onSelectedImages.emit(this, v);
            print(v);
          },
          isShowConsultationImage: false,
        ),
      );
    } else {
      Get.to(
        () => ExamImagesListView(
          cloudImageInfos: [cloudImageInfo],
          measureImages: measureImages,
          aiImages: aiImages,
          patientCode: widget.recordInfo.patientCode,
          patientName: widget.recordInfo.patientName,
          recordCode: recordCode,
        ),
      );
    }
  }

  ///提交报告
  Future<void> onSubmitReport(
      {String? templateJson,
      String? reportDataJson,
      bool resizeFactor = false,
      bool isLandscapeMode = false}) async {
    PromptBox.loading(i18nBook.common.submitting.t);
    var patientInfoDto = await remedicalManager
        .findPatientByCode(widget.recordInfo.patientCode!);
    var patientInfo = remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
    var recordDetail = await remedicalManager.queryRecordInfoAsync(recordCode);
    String reportDatasJson;
    var deviceOrganzationName = recordDetail?.deviceOrganzationName ?? '';
    var languageManager = Get.find<ILanguageConfigManager>();
    if (reportDataJson == null) {
      reportDatasJson = reportManager.getMobileReportDatasJson(
        patientName: patientInfo.name,
        patientSex: languageManager.getExamLanguageValue(patientInfo.sex ?? ''),
        age: patientInfo.age,
        imageInfos: _selectedRemedicalImages,
        des: _desController.text,
        summary: _consualationController.text,
        creatorName: recordDetail?.creatorName ?? '',
        fullName: Store.user.displayName,
        customDoctor: recordDetail?.customDoctor ?? '',
        customOrganzation: recordDetail?.customOrganzation ?? '',
        deviceOrganzationName: deviceOrganzationName,
      );
    } else {
      reportDatasJson = reportDataJson;
    }
    String defaultTemplate;
    if (templateJson == null) {
      defaultTemplate = await reportManager.getReportTemplate();
    } else {
      defaultTemplate = templateJson;
    }
    final addRequest = AddReportRequest(
        token: Store.user.token,
        patientName: FEncryptHelper.encodeBase64(patientInfo.name ?? ''),
        recordCode: recordCode,
        reportTemplateJson: defaultTemplate,
        reportDatasJson: reportDatasJson,
        platformLabels: ["Flyinsono", "Mobile", "RemoteDiagnosis"]);
    if (widget.recordInfo.referralType.index > 0) {
      ///转诊报告
      addRequest.isReferral = true;
    }
    final submitResult = await rpc.report.addReportAsync(addRequest);
    PromptBox.dismiss();
    if (submitResult.isNotEmpty) {
      PromptBox.toast(i18nBook.remedical.submitSuccessToCompleteList.t);
      Future.delayed(Duration(microseconds: 200), () {
        _onCreatePermissionChange.emit(this, false);
      });
    }
    _selectedRemedicalImages.clear();
    _desController.text = '';
    _consualationController.text = '';

    Future.delayed(Duration(milliseconds: 200), () {
      if (isLandscapeMode) {
        SystemChrome.setPreferredOrientations(
            [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
        router.back();
        router.back();
        router.back();
      } else {
        router.back();
        if (!resizeFactor) {
          router.back();
        }
      }
    });

    Get.find<IReportManager>().onMobileSubmitReport.emit(this, true);
    var reportList = await remedicalManager.findExamReports(recordCode);
    _reportList = reportList;
    _onReportsChange.emit(this, _reportList);
  }

  Future<void> editReport(
      {bool isLandscapeMode = false,
      bool resizeFactor = false,
      bool isNew = false}) async {
    bool isAnimailReport = false;
    try {
      var orgInfo = await Get.find<IUserInfoManager>()
          .getOrganizationByCode(Store.user.rootOrganizationCode ?? '');
      isAnimailReport =
          orgInfo.patientType == OrganizationPatientTypeEnum.Animals;
    } catch (e) {
      print(e);
    }
    TextEditingController? hospitalController;
    TextEditingController? ownerController;
    TextEditingController? nameController;
    TextEditingController? ageController;
    TextEditingController? speciesController;
    TextEditingController? inspectionPhysicianController;
    TextEditingController? reportPhysicianController;
    List<String>? genderItems;
    List<String>? speciesItems;
    ElementInfo? hospitalElement;
    ElementInfo? ownerElement;
    ElementInfo? nameElement;
    ElementInfo? genderElement;
    ElementInfo? ageElement;
    ElementInfo? idElement;
    ElementInfo? speciesElement;
    ElementInfo? inspectionPhysicianElement;
    ElementInfo? reportPhysicianElement;
    void Function(String)? onSelectedGender;
    void Function(String)? onSelectedSpecies;
    String? reportTemplate;

    if (isAnimailReport) {
      var patientInfoDto = await remedicalManager
          .findPatientByCode(widget.recordInfo.patientCode!);
      var patientInfo =
          remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
      var reportTemplateInfo =
          await Get.find<IReportTemplateManager>().getDefaultTemplate();
      reportTemplate = reportTemplateInfo.reportTemplateJson;

      if (reportTemplate.isNotNullOrEmpty) {
        var recordDetail =
            await remedicalManager.queryRecordInfoAsync(recordCode);
        var reportTempalteDoc =
            ReportTemplateDocument.fromJson(jsonDecode(reportTemplate!));
        report.FReportInfo.instance.init(
          reportTempalteDoc,
          DateTime.now(),
          "",
          revoke: i18nBook.common.revoke.t,
          selectEntry: i18nBook.remedical.selectWord.t,
          selectImageHint: i18nBook.remedical.clickAndSelectImage.t,
        );
        hospitalElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[0]);
        if (hospitalElement != null && hospitalElement is InputTextInfo) {
          hospitalController = TextEditingController();
          if (Store.user.rootOrganizationName.isEmpty) {
            hospitalController.text = recordDetail?.deviceOrganzationName ?? "";
          } else {
            hospitalController.text = Store.user.rootOrganizationName;
          }
        }
        ownerElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[1]);
        if (ownerElement != null && ownerElement is InputTextInfo) {
          ownerController = TextEditingController();
        }
        nameElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[2]);
        if (nameElement != null && nameElement is InputTextInfo) {
          nameController = TextEditingController();
          nameController.text = patientInfo.name ?? '';
        }
        genderElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[3]);
        if (genderElement != null && genderElement is SingleSelectedInfo) {
          genderItems = genderElement.items ?? [];
          onSelectedGender = (v) {
            _gender = v;
          };
        }

        ageElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[4]);
        if (ageElement != null && ageElement is InputTextInfo) {
          ageController = TextEditingController();
          ageController.text = patientInfo.ageYear ?? '';
        }
        idElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[5]);
        if (idElement != null && idElement is InputTextInfo) {
          if (patientInfoDto.devicePatientIDs?.isNotEmpty ?? false) {
            idElement.text = patientInfoDto.devicePatientIDs?.first ?? '';
          }
        }
        speciesElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[6]);
        if (speciesElement != null && speciesElement is SingleSelectedInfo) {
          speciesItems = speciesElement.items;
          onSelectedSpecies = (v) {
            _specie = v;
          };
        }
        inspectionPhysicianElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[7]);
        if (inspectionPhysicianElement != null &&
            inspectionPhysicianElement is InputTextInfo) {
          inspectionPhysicianController = TextEditingController();
          inspectionPhysicianController.text = Store.user.displayName;
        }
        reportPhysicianElement = report.FReportInfo.instance
            .getElementInfoByTagName(PETREPORTTAGS[8]);
        if (reportPhysicianElement != null &&
            reportPhysicianElement is InputTextInfo) {
          reportPhysicianController = TextEditingController();
          reportPhysicianController.text = Store.user.displayName;
        }
      }
    }
    await Get.to(
      () => WriteReport(
        isNew: isNew,
        isLandscapeMode: isLandscapeMode,
        selectedRemedicalImages: _selectedRemedicalImages,
        onSubmit: () {
          if (isAnimailReport) {
            if (hospitalElement != null && hospitalElement is InputTextInfo) {
              hospitalElement.text = hospitalController?.text ?? '';
            }
            if (ownerElement != null && ownerElement is InputTextInfo) {
              ownerElement.text = ownerController?.text ?? '';
            }
            if (nameElement != null && nameElement is InputTextInfo) {
              nameElement.text = nameController?.text ?? '';
            }
            if (genderElement != null && genderElement is SingleSelectedInfo) {
              genderElement.selectedItem = _gender;
            }
            if (ageElement != null && ageElement is InputTextInfo) {
              ageElement.text = ageController?.text ?? '';
            }
            if (speciesElement != null &&
                speciesElement is SingleSelectedInfo) {
              speciesElement.selectedItem = _specie;
            }
            if (inspectionPhysicianElement != null &&
                inspectionPhysicianElement is InputTextInfo) {
              inspectionPhysicianElement.text =
                  inspectionPhysicianController?.text ?? '';
            }
            if (reportPhysicianElement != null &&
                reportPhysicianElement is InputTextInfo) {
              reportPhysicianElement.text =
                  reportPhysicianController?.text ?? '';
            }

            var consualationElement = report.FReportInfo.instance
                .getElementInfoByTagName(TagNames.REPORTDES);
            if (consualationElement != null &&
                consualationElement is InputTextInfo) {
              consualationElement.text = _desController.text;
            }
            var desElement = report.FReportInfo.instance
                .getElementInfoByTagName(TagNames.REPORTSUMARY);
            if (desElement != null && desElement is InputTextInfo) {
              desElement.text = _consualationController.text;
            }
            var inputImageElement = report.FReportInfo.instance
                .getElementInfoByTagName(TagNames.SELECTIMAGES);
            if (inputImageElement != null &&
                inputImageElement is InputImageListInfo) {
              inputImageElement.selectedImages = _selectedRemedicalImages;
            }

            report.FReportInfo.instance.toJson();
            if (report.FReportInfo.instance.jsonItems.isNotEmpty) {
              var reportDataJson =
                  jsonEncode(report.FReportInfo.instance.jsonItems);
              onSubmitReport(
                reportDataJson: reportDataJson,
                templateJson: reportTemplate!,
                isLandscapeMode: isLandscapeMode,
                resizeFactor: resizeFactor,
              );
            }
          } else {
            onSubmitReport(
                isLandscapeMode: isLandscapeMode, resizeFactor: resizeFactor);
          }
        },
        onRemoveImage: (image) {
          if (_selectedRemedicalImages.contains(image)) {
            setState(() {
              _selectedRemedicalImages.remove(image);
            });
          }
        },
        conTextController: _consualationController,
        desTextController: _desController,
        onTapSelectImage: () async {
          await openImagesPage(
            isSelectImageModel: true,
          );
        },
        onSelectedImages: _onSelectedImages,
        hospitalController: hospitalController,
        ownerController: ownerController,
        nameController: nameController,
        ageController: ageController,
        speciesController: speciesController,
        inspectionPhysicianController: inspectionPhysicianController,
        reportPhysicianController: reportPhysicianController,
        genderItems: genderItems,
        speciesItems: speciesItems,
        onSelectedGender: onSelectedGender,
        onSelectedSpecies: onSelectedSpecies,
      ),
    );
    _selectedRemedicalImages.clear();
  }

  Future<void> onTapImage() async {
    List<RemedicalMeasuredInfoDTO> measureImages =
        await remedicalManager.findRemedicalMeasuredInfoAsync(recordCode);
    List<RemedicalAISelectedInfoDTO> aiImages = await remedicalManager
        .findAIImages(recordCode, widget.recordInfo.patientCode ?? "");
    RemedicalListResult cloudImageInfo =
        await reportManager.getRemedicalListByRecordInfoAsync(recordCode);
    await Get.to(
      () => ExamImagesListView(
        cloudImageInfos: [cloudImageInfo],
        measureImages: measureImages,
        aiImages: aiImages,
        recordCode: recordCode,
        patientCode: widget.recordInfo.patientCode,
        patientName: widget.recordInfo.patientName,
        isCanWriteReport: widget.recordInfo.isCanCreateReport,
        onRefreshCloudImages: () async {
          return [
            await reportManager.getRemedicalListByRecordInfoAsync(recordCode)
          ];
        },
      ),
    );
  }

  void onEditReport(Object sender, String recordCode) {
    if (recordCode == widget.recordInfo.recordCode) {
      editReport(isLandscapeMode: true);
    }
  }

  FWidget _buildStatus() {
    var recordStatus = widget.recordInfo.recordStatus;
    var referralType = widget.recordInfo.referralType;
    String label = '';
    if (referralType == ReferralTypeEnum.ReferralIn) {
      label += '(${i18nBook.remedical.transferiIn.t})';
    } else if (referralType == ReferralTypeEnum.ReferralOut) {
      label += '(${i18nBook.remedical.transferOut.t})';
    }
    return FRow(
      children: [
        const FSizedBox(width: FSpacings.M),
        FTitleField(
          i18nBook.common.status.t,
          FText(
            _stateLabel(recordStatus) + label,
            style: TextStyle(color: Colors.black87),
          ),
          minTitleWidth: 90,
          sizeBetween: _sizeBetween,
          isBold: false,
        ),
      ],
    );
  }
}
