import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:fis_ui/values/paddings.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/inspection_details_dialog.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/records_image_list.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/status_label.dart';

/// 检查卡片
class BuildCheckRecordCard extends FisView<ConsultationController>
    implements FInteractiveContainer {
  /// 检查记录时间
  final String? time;

  /// 下发设备
  final String? distributionEquipment;

  /// 部门
  final String? department;

  /// 检查医生
  final String? examiningDoctor;

  /// 报告数
  final int? reportsNum;

  /// 检查Code
  final String? recordCode;

  /// 检查状态
  final RecordStatusEnum? recordStatus;

  /// AI测量的器官
  final List<DiagnosisOrganEnum>? diagnosisOrgans;

  /// 是否是转诊
  final bool? isReferral;

  /// 转诊状态
  final ReferralStatusEnum? referralStatus;

  ///是否可创建报告
  final bool? canCreateReport;

  @override
  final String pageName;

  /// 当前检查的图片组
  final List<RemedicalInfoDTO>? remedicalList;
  final List<DiagnosisInfoDTO>? diagnosisInfos;

  /// 当前第几个检查
  final int? index;

  /// 设备码
  final String? deviceCode;

  /// 是否可以开始图片采集
  final bool? canStartImgCollecting;

  /// 外边距
  final EdgeInsets margin = const EdgeInsets.only(
    right: 20,
    left: 20,
    top: 20,
  );

  /// 内边距
  final EdgeInsets padding = const EdgeInsets.only(
    top: 20,
    left: 15,
  );

  /// 阴影
  final BoxShadow boxShadow = BoxShadow(
    color: FColorHelper.mixColor(
      Colors.black12,
      Colors.black38,
      70,
    ),
    offset: Offset(3.0, 3.0), //阴影y轴偏移量
    blurRadius: 6, //阴影模糊程度
    spreadRadius: 0, //阴影扩散程度
  );

  BuildCheckRecordCard({
    Key? key,
    this.time,
    this.distributionEquipment,
    this.department,
    this.examiningDoctor,
    this.reportsNum,
    this.recordCode,
    this.recordStatus,
    this.remedicalList,
    this.index,
    this.diagnosisOrgans = const [DiagnosisOrganEnum.Null],
    this.diagnosisInfos = const [],
    this.isReferral = false,
    this.pageName = 'CheckRecordCard',
    this.referralStatus = ReferralStatusEnum.Wait,
    this.canCreateReport,
    this.deviceCode,
    this.canStartImgCollecting,
  }) : super(key: key);

  /// 无检查列表
  bool get isNoRemedicalList => remedicalList!.toList().length == 0;

  /// 查看详情
  Future<void> viewDetails() async {
    await controller.inspectionRecordsController.getCheckInfo(recordCode!);
    router.dialog(
      () => InspectionDetailsDiaLog(
        recordCode: recordCode!,
        checkInfo: controller.state.checkLists[index!],
        patientInfo: controller.state.patientInfo,
        patientInfoExts: controller.state.checkInfoLists,
        patientType: controller.state.patientType,
      ),
    );
  }

  @override
  FWidget build(BuildContext context) {
    final child = FAnimatedContainer(
      duration: const Duration(milliseconds: 200),
      margin: margin,
      padding: padding,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.all(
          Radius.circular(8),
        ),
        boxShadow: [
          boxShadow,
        ],
      ),
      child: FColumn(
        mainAxisSize: MainAxisSize.min,
        children: [
          FContainer(
            child: _buildInspectionImageInfo(),
          ),
          FContainer(
            padding: EdgeInsets.all(10),
            margin: EdgeInsets.only(right: 15),
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(
                  color: Color.fromRGBO(216, 216, 216, 1),
                  width: 0.5,
                ),
              ),
            ),
            child: _buildActionBar(),
          ),
        ],
      ),
    );

    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      onEnter: (e) {},
      onExit: (e) {},
      child: FGestureDetector(
        name: "viewDetails",
        businessParent: this,
        onTap: () => viewDetails(),
        child: child,
      ),
    );
  }

  /// 文本
  FWidget _buildRowTitle(String title, dynamic value) {
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 120 : 180,
          height: 30,
          child: FText(
            title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        FExpanded(
          child: (value is String)
              ? FContainer(
                  height: 45,
                  child: FAlign(
                    alignment: Alignment.centerLeft,
                    child: FText(
                      value,
                    ),
                  ))
              : value,
        ),
      ],
    );
  }

  /// AI 图标
  FWidget _buildAIIcons() {
    return FRow(
      children: diagnosisInfos!
          .map(
            (e) => FIcon(
              _aiIconItem(
                e.diagnosisOrgan,
              ),
              size: 30,
              color: _buildAIIconColor(
                e.conclusion,
              ),
            ),
          )
          .toList(),
    );
  }

  Color _buildAIIconColor(DiagnosisConclusionEnum diagnosisConclusion) {
    switch (diagnosisConclusion) {
      case DiagnosisConclusionEnum.NoObviousLesion:
        return Colors.lightBlue;
      case DiagnosisConclusionEnum.Benign:
        return Colors.greenAccent;
      case DiagnosisConclusionEnum.BenignAndMalignant:
      case DiagnosisConclusionEnum.Malignant:
        return Colors.orangeAccent;
      case DiagnosisConclusionEnum.Other:
        return Colors.lightBlue;
      default:
        return Colors.black;
    }
  }

  IconData _aiIconItem(DiagnosisOrganEnum diagnosisOrganEnum) {
    switch (diagnosisOrganEnum) {
      case DiagnosisOrganEnum.Breast:
        return FIcons.mammary_gland;
      case DiagnosisOrganEnum.Liver:
        return FIcons.liver;
      case DiagnosisOrganEnum.Kidney:
        return FIcons.fis_kidney;
      case DiagnosisOrganEnum.Cholecyst:
        return FIcons.fis_gallbladder;
      case DiagnosisOrganEnum.Spleen:
        return FIcons.fis_spleen;
      case DiagnosisOrganEnum.Thyroid:
        return FIcons.fis_thyroid;
      case DiagnosisOrganEnum.CarotidArtery:
        return FIcons.arteria_carotis;
      default:
        // 图像待定
        return FIcons.arteria_carotis;
    }
    // return
  }

  /// 文本组
  FWidget _buildRowTitleList() {
    return FContainer(
      padding: EdgeInsets.only(
        left: 20,
        bottom: 10,
      ),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildRowTitle(
            i18nBook.remedical.time.t,
            time!,
          ),
          _buildRowTitle(
            i18nBook.remedical.organization.t,
            department!,
          ),
          _buildRowTitle(
            i18nBook.remedical.checkDoctor.t,
            _generatorDoc(),
          ),
          _buildRowTitle(
            i18nBook.remedical.deliveryDevice.t,
            distributionEquipment!,
          ),
          _buildRowTitle(
            i18nBook.common.report.t,
            reportsNum.toString(),
          ),
          _buildRowTitle(
            'AI${i18nBook.homePage.diagnostics.t}',
            _buildAIIcons(),
          ),
        ],
      ),
    );
  }

  String _generatorDoc() {
    return ((examiningDoctor == null || examiningDoctor!.isEmpty)
        ? i18nBook.homePage.notYet.t
        : examiningDoctor)!;
  }

  /// 状态tip
  FWidget _buildStateTip(RecordStatusEnum status) {
    switch (status) {
      case RecordStatusEnum.NotScanned:
        return StatusLabel(
          title: i18nBook.remedical.toScan4Label.t,
          color: _buildReportStatusColor(recordStatus!),
        );
      case RecordStatusEnum.NotReport:
        return StatusLabel(
          title: i18nBook.remedical.scanned4Label.t,
          color: _buildReportStatusColor(recordStatus!),
        );
      case RecordStatusEnum.Uploaded:
        return StatusLabel(
          title: i18nBook.remedical.imageUploaded4Label.t,
          color: _buildReportStatusColor(recordStatus!),
        );
      case RecordStatusEnum.Completed:
        return StatusLabel(
          title: i18nBook.remedical.reported4Label.t,
          color: _buildReportStatusColor(recordStatus!),
        );
      default:
        return StatusLabel(
          title: i18nBook.remedical.notFinished4Label.t,
          color: _buildReportStatusColor(recordStatus!),
        );
    }
  }

  Color? _buildReportStatusColor(RecordStatusEnum status) {
    if (status == RecordStatusEnum.Completed ||
        status == RecordStatusEnum.Uploaded)
      return Color.fromRGBO(124, 182, 90, 1);
    else {
      return Color.fromRGBO(
        240,
        141,
        46,
        1,
      );
    }
  }

  FWidget _buildTextButton(String textString, Function onPressed) {
    return FElevatedButton(
      name: textString,
      businessParent: this,
      onPressed: () => onPressed.call(),
      child: FText(
        textString,
      ),
      style: ButtonStyle(
        padding: MaterialStateProperty.all(
          EdgeInsets.symmetric(
            vertical: 8,
          ),
        ),
      ),
    );
  }

  /// 操作栏
  FWidget _buildActionBar() {
    /// 普通非转诊病人可以写报告的状态判断
    bool isCanWriteReport = [
          RecordStatusEnum.Uploaded,
          RecordStatusEnum.NotReport,
        ].contains(recordStatus) ||
        (canCreateReport ?? false);

    /// 转诊病人可以写报告的状态判断
    bool isReferralCanWriteReport = !isReferral! ||
        (isReferral! && referralStatus == ReferralStatusEnum.Accepted);
    if (!((RecordStatusEnum.Uploaded == recordStatus!) &&
        controller.state.isShowValid)) {
      print(recordStatus.toString());
      print(controller.state.isShowValid);
    }

    return FAlign(
      alignment: Alignment.centerRight,
      child: FButtonGroup(
        buttonPadding: FPaddings.MINI_BUTTON,
        spacing: FSpacings.MINI_BUTTON,
        children: [
          if ((RecordStatusEnum.Uploaded == recordStatus! ||
                  RecordStatusEnum.NotScanned == recordStatus!) &&
              controller.state.isShowValid &&
              !canStartImgCollecting!)
            _buildTextButton(
              i18nBook.remedical.endScan.t,
              () => controller.endScan(recordCode!, this),
            ),
          if (canStartImgCollecting!)
            _buildTextButton(
              i18nBook.remedical.startScan.t,
              () async {
                await controller.startScan(deviceCode!, recordCode!, this);
              },
            ),
          _buildTextButton(
            i18nBook.remedical.examinationDetails.t,
            () => viewDetails(),
          ),
          _buildTextButton(
            i18nBook.remedical.image.t,
            () => controller.inspectionRecordsController.getCheckScannedImage(
              recordCode!,
            ),
          ),
          _buildTextButton(i18nBook.common.report.t, () async {
            controller.inspectionRecordsController.openReportDialog(
              recordCode,
            );
          }),
          if (isCanWriteReport &&
              isReferralCanWriteReport &&
              Store.user.hasFeature(FeatureKeys.DiagnosisEditReport)) ...[
            _buildTextButton(i18nBook.remedical.writeReport.t, () async {
              await controller.inspectionReportController.openReportEdit(
                recordCode!,
                controller.state.patientCode,
                patientTab: controller.state.patientTab,
                referralRecordCode: controller.state.referralRecordCode,
              );
            }),
            // FElevatedButton.icon(
            //   businessParent: this,
            //   onPressed: () async =>
            //       await controller.inspectionReportController.openReportEdit(
            //     recordCode!,
            //     controller.state.patientCode,
            //     patientTab: controller.state.patientTab,
            //     referralRecordCode: controller.state.referralRecordCode,
            //   ),
            //   label: FText(
            //     i18nBook.remedical.writeReport.t,
            //   ),
            //   icon: const Icon(Icons.mode_edit),
            //   name: "writeReport",
            //   style: ButtonStyle(
            //     padding: MaterialStatePropertyAll(EdgeInsets.all(0)),
            //   ),
            // ),
          ],
        ],
      ),
    );
  }

  FWidget _buildInspectionImageInfo() {
    return FColumn(
      children: [
        FContainer(
          child: FRow(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FExpanded(
                flex: 2,
                child: _buildRowTitleList(),
              ),
              FExpanded(
                flex: 3,
                child: FColumn(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    FContainer(
                      child: FContainer(
                        alignment: Alignment.centerRight,
                        width: 240,
                        child: _buildStateTip(
                          recordStatus!,
                        ),
                      ),
                    ),
                    FPadding(
                      padding: EdgeInsets.only(right: 30),
                      child: FRow(
                        children: [
                          FExpanded(
                            child: isNoRemedicalList
                                ? const FSizedBox()
                                : RecordsImageList(
                                    remedicalList: remedicalList ?? [],
                                    index: index,
                                    recordCode: recordCode,
                                    key: ValueKey(
                                      recordCode,
                                    ),
                                  ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
