import 'package:fis_common/extensions/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:flyinsono/pages/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/exam_record_util.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:get/get.dart';

class ConsultationReportCards extends FisView<MobileConsultationController>
    implements FPage {
  @override
  String get pageName => 'ConsultationReportCard';

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: ExamRecordsMobileAppbar(
        title: FText(
          i18nBook.realTimeConsultation.consultationReport.t,
          style: TextStyle(
            fontSize: FFontSizes.H6,
            color: Colors.white,
          ),
        ),
        // isSingle: true,
      ),
      body: _buildReportsView(context),
      backgroundColor: Colors.grey[200],
    );
  }

  FWidget _buildReportsView(BuildContext context) {
    return FAlwaysScrollListView(
      scrollController: controller.reportController,
      child: QuickFWidget(ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
        child: FListView.builder(
          shrinkWrap: true,
          itemCount: controller.state.reportList.length,
          controller: controller.reportController,
          itemBuilder: (context, index) {
            final reportInfo = controller.state.reportList[index];
            return FGestureDetector(
              name: "findReports",
              businessParent: this,
              onTap: () async {
                controller.state.reportCode = reportInfo.reportCode ?? '';
                await controller.findReportByCodeAsync();
                final preList =
                    controller.state.reportInfo.reportPreviewList ?? [];
                if (preList.isEmpty) {
                  PromptBox.toast(i18nBook.remedical.reportNoInit.t);
                } else {
                  controller.state.reportIndex = index;
                  Get.to(() => ReportPreview(
                        reportInfo: controller.state.reportInfo,
                        reportList: controller.state.reportList,
                      ));
                }
              },
              child: _ReportCardMobileLayout(
                reportInfo,
                index,
                businessParent: this,
              ),
            );
          },
        ),
      )),
    );
  }
}

class _ReportCardMobileLayout extends FisView<MobileConsultationController> {
  final reportManager = Get.find<IReportManager>();
  final ReportDTO reportInfo;
  final int index;
  final double _cardHeight = 183;
  final double _reportPreviewWidth = 70.92;
  final double _reportPreviewHeight = 100;
  final double _reportIconSize = 70;

  ///父级节点
  final FInteractiveContainer businessParent;
  static const _textStyle = TextStyle(
    fontSize: FFontSizes.BODY,
  );
  _ReportCardMobileLayout(
    this.reportInfo,
    this.index, {
    required this.businessParent,
  });

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      height: _cardHeight,
      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,
      ),
      margin: EdgeInsets.only(left: 7, right: 7, top: 10),
      child: FColumn(
        children: [
          _buildReportInfoView(),
          const FSizedBox(height: 5),
          FDivider(
            height: 1,
            thickness: 1,
            color: Colors.grey[200],
          ),
          _buildReportOperateButtons(context, index, reportInfo),
        ],
      ),
    );
  }

  ///报告内容展示
  FWidget _buildReportInfoView() {
    final reportPreviewList = reportInfo.reportPreviewList ?? [];
    var reportPreview = '';
    if (reportPreviewList.isNotEmpty) {
      var token = reportPreviewList.first.fileToken;
      if (token.isNotNullOrEmpty) {
        var tokens = token!.split(';');
        if (tokens.isNotEmpty) {
          reportPreview = tokens.first;
        }
      }
    }
    String patientName =
        controller.state.currentConsultationDetail?.patientName ?? '';
    String reportUserName = reportInfo.reportUserName ?? '';
    if (reportUserName.isEmpty) {
      final labels = reportInfo.diagnosisLabels ?? [];
      reportUserName = labels.isNotEmpty
          ? reportInfo.diagnosisLabels![0]
          : i18nBook.homePage.notYet.t;
    }
    DateTime updateTime = reportInfo.updateTime ?? DateTime.now();
    return FContainer(
      margin: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
      child: FRow(children: [
        if (reportPreviewList.isNotEmpty && reportPreview.isNotEmpty) ...[
          FImage.network(
            reportPreview,
            width: _reportPreviewWidth,
            height: _reportPreviewHeight,
          ),
        ] else ...[
          FContainer(
            width: _reportPreviewWidth,
            height: _reportPreviewHeight,
            child: FIcon(
              FIcons.report_a4,
              size: _reportIconSize,
            ),
          )
        ],
        const FSizedBox(width: 15),
        FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FText(
              patientName,
              style: TextStyle(
                fontSize: FFontSizes.H5,
                fontWeight: FontWeight.bold,
              ),
            ),
            FText(
              reportManager.getTime(updateTime.toString()),
              style: _textStyle,
            ),
            FText(
              i18nBook.realTimeConsultation.consultationReport.t,
              style: _textStyle,
            ),
            FText(
              i18nBook.remedical.reporter.t + " " + reportUserName,
              style: _textStyle,
            ),
          ],
        ),
        FExpanded(child: FSizedBox()),
      ]),
    );
  }

  FWidget _buildReportOperateButtons(
      BuildContext context, int index, ReportDTO reportInfo) {
    return FExpanded(
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          FCustomFlatButton(
            i18nBook.remedical.share.t,
            () {
              controller.state.reportCode = reportInfo.reportCode ?? '';
              reportManager.showBottomSheet(reportInfo);
            },
            businessParent: this.businessParent,
          ),
          FVerticalDivider(
            width: 1,
            thickness: 1,
            color: Colors.grey[200],
          ),
          FCustomFlatButton(
            i18nBook.remedical.image.t,
            () async {
              controller.onTapConsultationImages();
            },
            businessParent: this.businessParent,
          ),
          if (reportInfo.canEditReport) ...[
            FVerticalDivider(
              width: 1,
              thickness: 1,
              color: Colors.grey[200],
            ),
            FCustomFlatButton(
              i18nBook.common.edit.t,
              () async {
                controller.state.reportCode = reportInfo.reportCode ?? '';
                controller.editReport();
              },
              businessParent: this.businessParent,
            ),
          ],
        ],
      ),
    );
  }
}
