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:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/status_label.dart';

/// 转诊历史卡片
class ReferHistoryCard extends FisView<ConsultationController>
    implements FPage {
  /// 检查记录时间
  final String? time;

  /// 转出机构
  final String? referralOutOrganization;

  /// 转诊事由
  final String? subjectMatter;

  /// 转出申请人
  final String? creator;

  /// 转出申请人Code
  final String? creatorCode;

  /// 转入机构
  final String? referralInOrganization;

  /// 转入机构code
  final String? referralInOrganizationCode;

  /// 转入医生
  final String? referralInUser;

  /// 转入医生code
  final String? referralInUserCode;

  /// 当前状态
  final ReferralStatusEnum? referralStatus;

  /// 当前转诊code
  final String? referralRecordCode;

  /// 病人code
  final String? patientCode;

  /// 拒绝原因
  final String? rejectReason;

  /// 修改转诊tab
  final VoidCallback? editRefer;

  @override
  final String pageName;

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

  /// 内边距
  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, //阴影扩散程度
  );

  /// 普通病人tab
  bool get isReferPatientTab => controller.state.patientTab == 1;

  ReferHistoryCard({
    Key? key,
    this.pageName = 'ReferHistoryCard',
    this.time,
    this.referralOutOrganization,
    this.subjectMatter,
    this.creator,
    this.referralInOrganization,
    this.referralInUser,
    this.referralStatus,
    this.referralRecordCode,
    this.editRefer,
    this.referralInOrganizationCode,
    this.referralInUserCode,
    this.patientCode,
    this.rejectReason,
    this.creatorCode,
  }) : super(key: key);

  @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(),
          ),
          referralStatus != ReferralStatusEnum.Accepted
              ? 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(),
                )
              : FContainer(),
        ],
      ),
    );

    return child;
  }

  /// 文本
  FWidget _buildRowTitle(String title, dynamic value, [Color? textColor]) {
    return FRow(
      children: [
        FContainer(
          width: 200,
          height: 30,
          child: FAlign(
            alignment: Alignment.centerLeft,
            child: FText(
              title,
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        FExpanded(
          child: (value is String)
              ? FContainer(
                  child: FText(
                    value,
                    style: TextStyle(
                      color: textColor ?? Colors.black,
                    ),
                  ),
                )
              : value,
        ),
      ],
    );
  }

  void setModifyState() {
    controller.state.subjectMatter = subjectMatter ?? '';
    controller.state.referralOrganizationCode =
        referralInOrganizationCode ?? '';
    controller.state.referralUserCode = referralInUserCode ?? '';
    controller.state.modifyReferralRecordCode = referralRecordCode ?? '';
    controller.inspectionRecordsController
        .getUserListAsync(controller.state.referralOrganizationCode!);
  }

  /// 文本组
  FWidget _buildRowTitleList() {
    return FExpanded(
      child: FContainer(
        padding: EdgeInsets.only(
          left: 20,
          bottom: 10,
        ),
        child: FColumn(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildRowTitle(
              i18nBook.remedical.transferTime.t,
              time ?? '',
            ),
            _buildRowTitle(
              i18nBook.remedical.transferOutAgency.t,
              referralOutOrganization ?? '',
            ),
            _buildRowTitle(
              i18nBook.remedical.transferSubjectMatter.t,
              subjectMatter ?? '',
            ),
            _buildRowTitle(
              i18nBook.remedical.transferApply.t,
              creator ?? '',
            ),
            _buildRowTitle(
              i18nBook.remedical.transferOrganization.t,
              referralInOrganization ?? '',
            ),
            _buildRowTitle(
              i18nBook.remedical.transferDoctor.t,
              referralInUser ?? '',
            ),
            if ((rejectReason != null) &&
                referralStatus == ReferralStatusEnum.Rejected)
              _buildRowTitle(
                i18nBook.user.refuseReason.t,
                rejectReason,
                Colors.red,
              )
          ],
        ),
      ),
    );
  }

  /// 状态tip
  FWidget _buildStateTip(ReferralStatusEnum referralStatus) {
    switch (referralStatus) {
      case ReferralStatusEnum.Wait:
        return StatusLabel(
          title: i18nBook.remedical.pending.t,
          color: _buildReportStatusColor(referralStatus),
        );
      case ReferralStatusEnum.Withdrawn:
        return StatusLabel(
          title: i18nBook.remedical.hasWithDrawn.t,
          color: _buildReportStatusColor(referralStatus),
        );
      case ReferralStatusEnum.TimedOut:
        return StatusLabel(
          title: i18nBook.remedical.timedOut.t,
          color: _buildReportStatusColor(referralStatus),
        );
      case ReferralStatusEnum.Accepted:
        return StatusLabel(
          title: i18nBook.remedical.accepted.t,
          color: _buildReportStatusColor(referralStatus),
        );
      case ReferralStatusEnum.Rejected:
        return StatusLabel(
          title: i18nBook.remedical.refused.t,
          color: _buildReportStatusColor(referralStatus),
        );
      default:
        return StatusLabel(
          title: i18nBook.remedical.pending.t,
          color: _buildReportStatusColor(referralStatus),
        );
    }
  }

  Color? _buildReportStatusColor(ReferralStatusEnum status) {
    if (status == ReferralStatusEnum.Accepted)
      return Color.fromRGBO(124, 182, 90, 1);
    else {
      return Color.fromRGBO(
        240,
        141,
        46,
        1,
      );
    }
  }

  FWidget _buildTextButton(String text, Function onPressed,
      [Color? textColors]) {
    return FTextButton(
      name: "$text",
      businessParent: this,
      onPressed: () => onPressed.call(),
      style: ButtonStyle(
        side: MaterialStateProperty.all(
          BorderSide(
            color: Colors.grey,
            width: 0.5,
          ),
        ),
      ),
      child: FText(
        text,
        style: TextStyle(
          fontSize: 14,
          color: textColors ?? FTheme.ins.colorScheme.primary,
        ),
      ),
    );
  }

  /// 操作栏
  /// 新增作为转诊历史转给第三方
  /// 同意和拒绝按钮显示条件，转入医师code是否和当前医生code相同 or 是当前转入机构的机构管理员
  FWidget _buildActionBar() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        if (!isReferPatientTab || creatorCode == Store.user.code)
          if ([ReferralStatusEnum.Wait].contains(referralStatus))
            _buildTextButton(
              i18nBook.remedical.WithDrawn.t,
              () {
                controller.inspectionRecordsController
                    .withdrawReferralRecordAsync(
                  referralRecordCode!,
                  patientCode!,
                );
              },
            )
          else if ([
            ReferralStatusEnum.Withdrawn,
            ReferralStatusEnum.Rejected,
            ReferralStatusEnum.TimedOut,
            ReferralStatusEnum.Withdrawn
          ].contains(referralStatus))
            _buildTextButton(
              i18nBook.common.modify.t,
              () {
                setModifyState();
                editRefer?.call();
              },
            )
          else
            FContainer()
        else ...[
          ([ReferralStatusEnum.Wait].contains(referralStatus) &&
                  ((referralInUserCode == Store.user.code) ||
                      (Store.user.rootOrganizationCode ==
                              referralInOrganizationCode &&
                          Store.user.isPrincipal)))
              ? FRow(
                  children: [
                    _buildTextButton(
                      i18nBook.remedical.agree.t,
                      () {
                        controller.inspectionRecordsController
                            .auditReferralRecordAsync(
                          referralRecordCode!,
                          true,
                        );
                      },
                    ),
                    FSizedBox(
                      width: 15,
                    ),
                    _buildTextButton(
                      i18nBook.user.refuse.t,
                      () {
                        controller.openConfirmReferral(referralRecordCode!);
                      },
                      Colors.red,
                    )
                  ],
                )
              : FContainer()
        ]
      ],
    );
  }

  FWidget _buildInspectionImageInfo() {
    return FColumn(
      children: [
        FRow(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FContainer(
              alignment: Alignment.centerRight,
              /// TODO:[Gavin] 多语言-UI-整合
              width: i18nBook.isCurrentChinese ? 120 : 200,
              child: _buildStateTip(
                referralStatus ?? ReferralStatusEnum.Wait,
              ),
            ),
          ],
        ),
        FContainer(
          child: FRow(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildRowTitleList(),
            ],
          ),
        ),
      ],
    );
  }
}
