import 'package:fis_common/index.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/hover_text_button.dart';
import 'package:fis_ui/values/paddings.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/report/ai_icon_color.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/status_label.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'expand_buttons.dart';

class BuildReportRecord extends FStatelessWidget implements FPage {
  /// 当前报告的数据
  final ReportDTO currReport;

  ///病人名字
  final String? patientName;

  /// 是否是扫查图像的关联报告入口

  final bool? isInspectionReport;

  @override
  final String pageName;

  ///编辑报告
  final void Function()? onEditReport;

  ///编辑报告标签
  final void Function()? onEditReportTag;

  ///检查
  final void Function()? onExamTap;

  ///图像
  final void Function()? onImageTap;

  ///是否可编辑
  final bool canEditReport;

  final bool isSmailCard;

  final _reportManager = Get.find<IReportManager>();

  BuildReportRecord({
    Key? key,
    required this.currReport,
    this.patientName,
    this.isInspectionReport = false,
    this.pageName = 'BuildRecord',
    this.onEditReport,
    this.onExamTap,
    this.onEditReportTag,
    this.onImageTap,
    this.isSmailCard = false,
    required this.canEditReport,
  }) : super(key: key);

  static const String C_REPORTFORMAT = ".pdf";
  static const String C_DEFAULTFILENAME = "report";

  FWidget textButton(String textString, Function onPressed) {
    return FOutlinedButton(
      onPressed: () => onPressed.call(),
      child: FText(
        textString,
        style: TextStyle(color: Colors.black),
      ),
      style: ButtonStyle(
        padding: MaterialStateProperty.all(
            EdgeInsets.symmetric(horizontal: isSmailCard ? 5 : 0)),
        fixedSize: isSmailCard
            ? MaterialStateProperty.all<Size>(
                Size(75, 25),
              )
            : null,
      ),
      businessParent: this,
      name: '$textString',
    );
  }

  @override
  FWidget build(BuildContext context) {
    var margin = const EdgeInsets.only(right: 20, left: 20, top: 20);
    var color = Colors.white;
    var padding = const EdgeInsets.only(top: 5, left: 15);
    var boxShadow = BoxShadow(
      color: FColorHelper.mixColor(Colors.black12, Colors.black38, 70),
      offset: Offset(3.0, 3.0), //阴影y轴偏移量
      blurRadius: 6, //阴影模糊程度
      spreadRadius: 0, //阴影扩散程度
    );

    final child = FAnimatedContainer(
      duration: const Duration(milliseconds: 200),
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.all(
          Radius.circular(8),
        ),
        boxShadow: [
          boxShadow,
        ],
      ),
      child: FStack(
        children: [
          FColumn(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildRecordContent(context),
              if (isSmailCard) _buildReportTags(context),
              FContainer(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 10),
                margin: EdgeInsets.only(right: 15, top: 10),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: Color.fromRGBO(216, 216, 216, 1),
                      width: 0.5,
                    ),
                  ),
                ),
                child: isSmailCard
                    ? _buildSmailCardButtons()
                    : FFittedBox(
                        alignment: Alignment.centerRight,
                        fit: BoxFit.scaleDown,
                        child: _buildOperateButtons(),
                      ),
              ),
            ],
          ),
          FPositioned(
            right: 0,
            top: 30,
            child: _buildTag(currReport.referralRecordCode ?? ''),
          ),
        ],
      ),
    );

    return FColumn(
      children: [
        child,
      ],
    );
  }

  String? _generateNailUrl(ReportDTO reportList) {
    if (reportList.reportPreviewList == null ||
        reportList.reportPreviewList!.length == 0) {
      return null;
    }
    return reportList.reportPreviewList!.first.thumbnailToken;
  }

  /// 获取由 jpg url 类型的数据地址列表，例如："http://url1.jpg;http://url2.jpg;http://url3.jpg"
  /// 此处需要先拼接成字符串，再拆分成列表，是因为在某些情况下，返回的 fileToken 是带有多个 jpg url 的字符串，例如："http://url1.jpg;http://url2.jpg;http://url3.jpg"
  String? _generateReportUrl(ReportDTO reportList) {
    if (reportList.reportPreviewList == null ||
        reportList.reportPreviewList!.length == 0) {
      return null;
    }
    String fileToken = reportList.reportPreviewList!
        .where((e) => e.fileType != UploadFileTypeEnum.PDF)
        .map((e) => e.fileToken!)
        .toList()
        .join(';');
    return fileToken;
  }

  /// 获取 pdf url 类型的数据地址列表
  List<String> _generateReportPdfUrl(ReportDTO reportList) {
    if (reportList.reportPreviewList == null ||
        reportList.reportPreviewList!.length == 0) {
      return [];
    }
    List<String> fileTokens = reportList.reportPreviewList!
        .where((e) => e.fileType == UploadFileTypeEnum.PDF)
        .map((e) => e.fileToken!)
        .toList();
    return fileTokens;
  }

  String get _currReportImagesUrls => _generateReportUrl(currReport) ?? '';
  List<String> get _currReportImagesUrlList =>
      _currReportImagesUrls.isEmpty ? [] : _currReportImagesUrls.split(";");
  List<String> get _currReportPdfUrlList => _generateReportPdfUrl(currReport);
  FWidget _generateReportIcon(String? reportNailUrl) {
    var useDefaultImage = reportNailUrl == null || reportNailUrl.isEmpty;
    return FCenter(
      child: useDefaultImage
          ? FIcon(
              FIcons.report_a4,
              size: 70,
            )
          : FImage.network(
              reportNailUrl,
              fit: BoxFit.fill,
              width: 70,
              height: 100,
            ),
    );
  }

  ///标签
  FWidget _buildTag(String referralRecordCode) {
    if (referralRecordCode.isNotEmpty)
      return StatusLabel(
        title: i18nBook.remedical.referralReport.t,
        color: Color.fromRGBO(124, 182, 90, 1),
      );
    else
      return FSizedBox();
  }

  String _generateReaportFileName() {
    final nameStr = patientName!.replaceAll("*", "x");
    DateFormat format = DateFormat("yyyMMddHHmmss");
    final reportTimeStr = format.format(currReport.reportTime!.toLocal());
    final patientIdStr = currReport.patientId ?? i18nBook.remedical.notFill.t;
    final fileName = "${nameStr}_${patientIdStr}_$reportTimeStr$C_REPORTFORMAT";
    return fileName;
  }

  /// AI 图标
  FWidget _buildAIIcons(DiagnosisOrganEnum diagnosisOrgan) {
    Color aiColor = Colors.black;

    /// 老数据没有当前AI的良恶性状态 兼容老数据
    /// 老数据： ["VAid"] / 新数据： ["VAid", "BenignAndMalignant"]
    if (currReport.diagnosisLabels?.length == 2) {
      aiColor = AIIcon.buildAIIconColor(
        currReport.diagnosisLabels![1],
      );
    }

    return FIcon(
      AIIcon.buildAIIcon(
        diagnosisOrgan,
      ),
      color: aiColor,
      size: 30,
    );
  }

  ///报告标签列表
  FWidget _buildReportTags(BuildContext context) {
    final tags = currReport.reportLabels ?? [];
    return FContainer(
      width: MediaQuery.of(context).size.width,
      child: FWrap(
        direction: Axis.horizontal,
        alignment: WrapAlignment.start,
        children: tags
            .map(
              (e) => FContainer(
                height: 22,
                margin: EdgeInsets.only(right: 15, top: 3),
                child: FContainer(
                  decoration: new BoxDecoration(
                    borderRadius: BorderRadius.all(
                      Radius.circular(
                        4.0,
                      ),
                    ), //圆角弧度
                    border: new Border.all(
                      width: 1,
                      color: FTheme.ins.colorScheme.primary,
                    ),
                  ),
                  child: FContainer(
                    margin: EdgeInsets.symmetric(horizontal: 5),
                    child: FText(e),
                  ),
                ),
              ),
            )
            .toList(),
      ),
    );
  }

  ///操作按钮
  FWidget _buildOperateButtons() {
    return FButtonGroup(
      buttonPadding: FPaddings.MINI_BUTTON,
      spacing: FSpacings.MINI_BUTTON,
      children: [
        textButton(i18nBook.common.view.t, _openReportPreviewPage),
        if (!isInspectionReport!) ...[
          if (canEditReport &&
              Store.user.hasFeature(FeatureKeys.DiagnosisEditReport)) ...[
            textButton(i18nBook.common.modify.t, onEditReport!),
          ],
          if (Store.user.hasFeature(FeatureKeys.EditReportTag))
            textButton(i18nBook.remedical.addTag.t, onEditReportTag!),
          if (onExamTap != null)
            textButton(i18nBook.remedical.check.t, onExamTap!),
          if (onImageTap != null)
            textButton(i18nBook.remedical.image.t, onImageTap!),
        ],
        textButton(i18nBook.remedical.print.t, handlePrint),
        textButton(i18nBook.remedical.export.t, handleExport),
        textButton(i18nBook.remedical.share.t, shareReport),
      ],
    );
  }

  void shareReport() {
    ///TODO（Loki）：此处需拆分ConsultationController依赖
    Get.put(ConsultationController());
    _reportManager.openReportShareDialog(currReport.reportCode);
  }

  void handlePrint() async {
    final fileName = _generateReaportFileName();

    /// 优先尝试使用 PDF
    if (_currReportPdfUrlList.isNotEmpty) {
      print("currReportPdfUrl ${_currReportPdfUrlList[0]}");
      await _reportManager.directlyPrintPDFFile(
          _currReportPdfUrlList[0], fileName);
      // PDFHelper.printPDF(
      //   fileName,
      // );
      return;
    }

    if (_currReportImagesUrlList.isEmpty) {
      await _reportManager.directlyPrintPDF(
          currReport.reportCode ?? '', fileName);
    } else {
      await _reportManager.directlyPrintPDFJpges(
          _currReportImagesUrlList, fileName);
    }
  }

  void handleExport() async {
    final fileName = _generateReaportFileName();

    /// 优先尝试使用 PDF
    if (_currReportPdfUrlList.isNotEmpty) {
      print("currReportPdfUrl ${_currReportPdfUrlList[0]}");
      await _reportManager.directlyDownloadPDFFile(
          _currReportPdfUrlList[0], fileName);
      return;
    }
    if (_currReportImagesUrlList.isEmpty) {
      await _reportManager.directlyDownloadPDF(
          currReport.reportCode ?? '', fileName);
    } else {
      await _reportManager.directlyDownloadPDFJpges(
          _currReportImagesUrlList, fileName);
    }
  }

  void _openReportPreviewPage() {
    if (onExamTap == null && !isSmailCard) {
      router.back();
    }
    _reportManager.openReportPreviewPage(
      currReport.recordCode ?? '',
      currReport.referralRecordCode ?? '',
      reportCode: currReport.reportCode ?? '',
    );
  }

  FWidget _buildRecordContent(BuildContext context) {
    String reportJsonName = patientName ?? '';
    if (reportJsonName.isEmpty) {
      reportJsonName = i18nBook.remedical.notFill.t;
    }
    bool isAIReport = false;
    final diagnosisLabels = currReport.diagnosisLabels ?? [];
    if (diagnosisLabels.contains('VAid')) {
      isAIReport = true;
    }
    String reportUserName = currReport.reportUserName ?? '';
    if (reportUserName.isEmpty) {
      final labels = currReport.diagnosisLabels ?? [];
      reportUserName = labels.isNotEmpty
          ? currReport.diagnosisLabels![0]
          : i18nBook.homePage.notYet.t;
    }
    QualifiedState qualityType = currReport.qualifiedState;
    return FContainer(
      child: FRow(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FContainer(
            margin: EdgeInsets.only(
              bottom: 15,
            ),
            child: _generateReportIcon(_generateNailUrl(currReport)),
          ),
          FSizedBox(width: 15),
          FExpanded(
            child: FColumn(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FRow(
                  children: [
                    if (!isSmailCard) ...[
                      FExpanded(
                        child: FHoverTextButton(
                          businessParent: this,
                          name: "preview:$reportJsonName",
                          onTap: () {
                            _openReportPreviewPage();
                          },
                          label: reportJsonName,
                          color: FTheme.ins.colorScheme.primary,
                          hoverColor: FTheme.ins.colorScheme.secondary,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                    FContainer(
                      margin: EdgeInsets.only(
                        right: 15,
                      ),
                      child: FText(
                        _reportManager.getTime(
                          currReport.updateTime.toString(),
                        ),
                      ),
                    ),
                  ],
                ),
                FSizedBox(
                  height: 5,
                ),
                FText(
                  isAIReport
                      ? i18nBook.remedical.aiReport.t
                      : i18nBook.remedical.cloudReport.t,
                ),
                FSizedBox(
                  height: 5,
                ),
                FRow(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    FText(i18nBook.remedical.reporter.t),
                    FExpanded(
                      child: FText(
                        reportUserName,
                        // overflow: TextOverflow.fade,
                      ),
                    ),
                  ],
                ),
                if (currReport.reportOrgan != DiagnosisOrganEnum.Null &&
                    diagnosisLabels.length != 0 &&
                    isAIReport) ...[
                  FRow(
                    children: [
                      FText('AI${i18nBook.homePage.diagnostics.t}：'),
                      _buildAIIcons(currReport.reportOrgan),
                    ],
                  ),
                ],
                if (!isSmailCard) ...[
                  _buildReportTags(context),
                ],

                /// TODO 【质控功能暂时屏蔽，后面放开只要解开注释】
                // if (currReport.isQualityControlled &&
                //     Store.user.hasFeature(FeatureKeys.QualityControl)) ...[
                //   FSizedBox(
                //     height: 5,
                //   ),
                //   FText(i18nBook.common.qualityControlled.t),
                // ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildSmailCardButtons() {
    final Map<String, void Function()> operates = {
      i18nBook.common.view.t: _openReportPreviewPage,
    };
    if (Store.user.hasFeature(FeatureKeys.DiagnosisEditReport) &&
        canEditReport) {
      operates.addAll({i18nBook.common.modify.t: onEditReport!});
    }
    if (Store.user.hasFeature(FeatureKeys.EditReportTag)) {
      operates.addAll({i18nBook.remedical.addTag.t: onEditReportTag!});
    }
    operates.addAll({
      i18nBook.remedical.print.t: handlePrint,
      i18nBook.remedical.export.t: handleExport,
      i18nBook.remedical.share.t: shareReport,
    });

    return FExpandedButtons(operates, textButton, canEditReport);
  }
}
