import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/entities/report_element_info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:fis_theme/theme.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_images_view.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/reportinfo_card_mobile.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/write_report.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/widgets/scroll/refreshIndicator.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_common/logger/logger.dart';

class MobileReportsContentView extends FStatefulWidget
    implements FInteractiveContainer {
  @override
  final String pageName;
  final List<ReportDTO> reportList;
  final void Function(int) onTapCard;
  final void Function(int) onTapImage;
  final void Function(String) onTapShare;
  final void Function()? onTapCheck;
  final void Function()? onEditReport;
  final FEventHandler<List<ReportDTO>>? onReportsChange;
  final FEventHandler<bool>? onCreatePermissionChange;
  final bool isCanWriteReport;
  final bool isLandscapeMode;
  final Future<List<ReportDTO>> Function() onRefresh;
  final String? recordCode;
  final PatientInfo patientInfo;
  String get patientName => patientInfo.name ?? '';
  MobileReportsContentView({
    required this.reportList,
    required this.onTapCard,
    required this.onTapShare,
    required this.onRefresh,
    required this.onTapImage,
    required this.patientInfo,
    this.isLandscapeMode = false,
    this.isCanWriteReport = false,
    this.onTapCheck,
    this.onEditReport,
    this.recordCode,
    this.onReportsChange,
    this.pageName = 'MobileReportsContentView',
    this.onCreatePermissionChange,
  });

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

class MobileReportsContentViewState extends FState<MobileReportsContentView> {
  final reportManager = Get.find<IReportManager>();

  final FEventHandler<List<String>> onSelectedImages =
      FEventHandler<List<String>>();
  final remedicalManager = Get.find<IRemedicalManager>();
  final consualationController = TextEditingController();
  final desController = TextEditingController();
  List<String> _selectedImages = [];
  final _reportScrollController = ScrollController();
  bool _isCanWriteReport = false;
  List<ReportDTO> _reportList = [];
  @override
  void initState() {
    _isCanWriteReport = widget.isCanWriteReport;
    _reportList = widget.reportList;
    widget.onReportsChange?.addListener(_onReportsChange);
    widget.onCreatePermissionChange?.addListener(_onEditPermissionChange);
    super.initState();
  }

  void _onReportsChange(sender, List<ReportDTO> e) {
    setState(() {
      _reportList = e;
    });
  }

  @override
  void dispose() {
    widget.onCreatePermissionChange?.removeListener(_onEditPermissionChange);
    widget.onReportsChange?.removeListener(_onReportsChange);
    if (widget.isLandscapeMode) {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    }
    super.dispose();
  }

  @override
  void didUpdateWidget(MobileReportsContentView oldWidget) {
    if (_reportList != widget.reportList) {
      setState(() {
        _reportList = widget.reportList;
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: FAppBar(
        title: FText(i18nBook.remedical.checkReport.t),
        backgroundColor: FTheme.ins.colorScheme.primary,
        elevation: 0,
        centerTitle: true,
        leading: FIconButton(
          icon: FIcon(Icons.arrow_back_ios_new),
          onPressed: () {
            final currentRouter = router.getCurrentNameByNavId(NavIds.HOME);
            if (currentRouter == RouteNames.Remedical.ConsultationRecordView) {
              router.back();
            } else {
              router.offAll(RouteNames.Remedical.ConsultationRecordView,
                  id: NavIds.HOME);
            }
          },
          businessParent: widget,
          name: "back",
        ),
        actions: [
          if (_isCanWriteReport) ...[
            FIconButton(
              icon: FIcon(Icons.add),
              onPressed: () async {
                widget.onEditReport?.call();
              },
              businessParent: widget,
              name: 'edit',
            )
          ] else ...[
            FIconButton(
              icon: FIcon(Icons.refresh),
              onPressed: () async {
                var reportList = await widget.onRefresh.call();
                setState(() {
                  _reportList = reportList;
                });
              },
              businessParent: widget,
              name: 'refersh',
            )
          ],
        ],
      ),
      body: _buildReportsView(context),
      backgroundColor: Colors.grey[200],
    );
  }

  ///报告列表视图
  FWidget _buildReportsView(BuildContext context) {
    if (_reportList.isEmpty) {
      return FContainer(
        margin: EdgeInsets.only(top: 80),
        child: FColumn(
          children: [
            FCenter(
              child: FImage.asset(
                "assets/images/no_data.png",
                width: 300,
                height: 300,
                fit: BoxFit.cover,
              ),
            ),
            FText(i18nBook.common.noneDataTip.t),
          ],
        ),
      );
    }
    return FRefreshIndicator(
      onRefresh: () async {
        var reportList = await widget.onRefresh.call();
        setState(() {
          _reportList = reportList;
        });
      },
      child: FAlwaysScrollListView(
        scrollController: _reportScrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView.builder(
            shrinkWrap: true,
            itemCount: _reportList.length,
            controller: _reportScrollController,
            itemBuilder: (context, index) {
              final reportInfo = _reportList[index];
              return FGestureDetector(
                name: "findReports",
                businessParent: widget,
                onTap: () async {
                  widget.onTapCard.call(index);
                },
                child: ReportCardMobileLayout(
                  reportInfo,
                  index,
                  onTapEditReport: () =>
                      editReport(reportInfo.reportCode ?? ''),
                  businessParent: widget,
                  patientName: widget.patientName,
                  onTapShare: widget.onTapShare,
                  onTapImage: widget.onTapImage,
                ),
              );
            },
          ),
        )),
      ),
    );
  }

  void _onEditPermissionChange(Object sender, bool e) {
    setState(() {
      _isCanWriteReport = e;
    });
  }

  Future<void> editReport(String reportCode) async {
    var report = await reportManager.findReportByCodeAsync(reportCode);
    final jsonStr = report.reportDatasJson ?? '';
    var reportElements = reportManager.convertReportData(jsonStr);
    var imageElement = reportElements.firstWhereOrNull(
        (element) => element.name == FReportElementNames.ReportImages);

    if (imageElement != null && imageElement.value != null) {
      var imageValues = imageElement.value as List<dynamic>;
      if (imageValues.isNotEmpty) {
        _selectedImages = imageValues.map((e) => e.toString()).toList();
      }
    }
    var reportSummaryElement = reportElements.firstWhereOrNull(
        (element) => element.name == FReportElementNames.ReportSummary);
    if (reportSummaryElement != null && reportSummaryElement.value != null) {
      consualationController.text = reportSummaryElement.value;
    }
    var desElement = reportElements.firstWhereOrNull(
        (element) => element.name == FReportElementNames.ReportDescription);
    if (desElement != null && desElement.value != null) {
      desController.text = desElement.value;
    }
    await Get.to(
      () => WriteReport(
        isNew: false,
        selectedRemedicalImages: _selectedImages,
        onSubmit: () {
          _onsubmit(reportCode);
        },
        onRemoveImage: (image) {
          if (_selectedImages.contains(image)) {
            _selectedImages.remove(image);
          }
        },
        conTextController: consualationController,
        desTextController: desController,
        onTapSelectImage: _onTapSelectedImage,
        onSelectedImages: onSelectedImages,
      ),
    );
    _reportList = await reportManager.findReportsAsync(widget.recordCode ?? '');
  }

  Future<void> _onTapSelectedImage() async {
    var measureImages = await remedicalManager
        .findRemedicalMeasuredInfoAsync(widget.recordCode ?? '');
    var cloudImageInfos = await reportManager
        .getRemedicalListByRecordInfoAsync(widget.recordCode ?? '');

    await Get.to(
      () => ExamImagesView(
        measureImages: measureImages,
        consultationImages: [],
        patientCode: widget.patientInfo.patientCode,
        cloudImageInfos: [cloudImageInfos],
        isSelectImageModel: true,
        isSingle: true,
        onSubmit: (List<String> v) {
          _selectedImages = v;
        },
        selectedImags: _selectedImages,
        isShowConsultationImage: false,
      ),
    );
  }

  ///提交报告
  Future<void> _onsubmit(String reportCode) async {
    Store.app.setBusy(i18nBook.common.submitting.t);
    bool submitResult = false;
    try {
      var patientInfo = widget.patientInfo;
      var patientName = patientInfo.name ?? '';
      var recordDetail =
          await remedicalManager.queryRecordInfoAsync(widget.recordCode ?? '');
      var languageManager = Get.find<ILanguageConfigManager>();
      var deviceOrganzationName = recordDetail?.deviceOrganzationName ?? '';
      final reportDatasJson = reportManager.getMobileReportDatasJson(
        patientName: patientName,
        patientSex: languageManager.getExamLanguageValue(patientInfo.sex ?? ''),
        age: patientInfo.ageYear,
        imageInfos: _selectedImages,
        des: desController.text,
        summary: consualationController.text,
        creatorName: Store.user.displayName,
        fullName: Store.user.displayName,
        deviceOrganzationName: deviceOrganzationName,
      );
      final reportInfo =
          await rpc.report.findReportByCodeAsync(FindReportByCodeRequest(
        token: Store.user.token,
        reportCode: reportCode,
      ));
      var defaultTemplate = await reportManager.getReportTemplate();
      submitResult = await rpc.report.modifyReportAsync(
        ModifyReportRequest(
          reportType: ReportTypeEnum.RemoteDiagnosis,
          token: Store.user.token,
          patientName: FEncryptHelper.encodeBase64(patientName),
          recordCode: widget.recordCode,
          reportTemplateJson: defaultTemplate,
          reportDatasJson: reportDatasJson,
          platformLabels: ["Flyinsono", "Mobile", "Remedical"],
          reportCode: reportCode,
          reportOrgan: reportInfo.reportOrgan,
        ),
      );
    } catch (e) {
      logger.e('save report error:', e);
    }
    Store.app.busy = false;

    if (submitResult) {
      PromptBox.toast(i18nBook.remedical.submitSuccess.t);
      router.back();
      _selectedImages = [];
      desController.text = '';
      consualationController.text = '';
      Future.delayed(Duration(milliseconds: 500), () async {
        var reportList = await widget.onRefresh.call();
        widget.onReportsChange?.emit(this, reportList);
        setState(() {
          _reportList = reportList;
        });
      });
    }
  }
}
