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/values/font_sizes.dart';
import 'package:fis_ui/widgets/checkbox/rectangle_checkbox.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/age_text.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/associat_patient.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/patient_card_mobile.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/status_label.dart';
import 'package:get/get.dart';

///病人信息卡片
class PatientCard extends StatefulWidget implements FPage {
  PatientCard(this.index, this.patientInfo,
      {this.pageName = 'PatientCard', Key? key});

  ///病人信息索引
  final int index;
  @override
  final String pageName;

  ///病人信息词典
  final PatientInfo? patientInfo;

  @override
  State<StatefulWidget> createState() => _PatientCardState();
}

class _PatientCardState extends State<PatientCard> {
  bool hovering = false;
  final controller = Get.find<ConsultationController>();
  bool get isShowReferral => widget.patientInfo!.isValid ?? true;

  bool get isActive => isPatientTab
      ? controller.state.patientCode == widget.patientInfo?.patientCode
      : controller.state.referralRecordCode ==
          widget.patientInfo?.referralRecordCode;

  /// 我的病人tab
  bool get isPatientTab => controller.state.patientTab == 0;

  Color get lightColorWhenActive => isActive ? Colors.white : Colors.black87;

  final buttonStyle = ElevatedButton.styleFrom(
    minimumSize: Size(60, 30),
    maximumSize: Size(60, 30),
    alignment: Alignment.center,
  );

  @override
  FWidget build(BuildContext context) {
    if (kIsMobile) {
      return PatientCardMobileLayout(widget.index, widget.patientInfo);
    } else {
      return _buildDesktopLayout();
    }
  }

  FWidget _buildDesktopLayout() {
    String avatar = ' ';
    final name = (widget.patientInfo!.name);
    if (name != null) {
      if (name.toString().isNotEmpty) {
        avatar = name.toString().substring(0, 1);
      }
    }
    var dividerLength = EdgeInsets.only(right: 15);
    if (!isActive) {
      dividerLength = EdgeInsets.only(right: 22);
    }

    final child = FStack(
      children: [
        FObx(
          () => SwipeCard(
            index: widget.index,
            isActive: isActive,
            onTap: () {
              controller.clickPatientCard(
                widget.index,
                widget.patientInfo!,
              );
            },
            child: FColumn(
              children: [
                FRow(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  //病人信息
                  children: [
                    _buildCheckBox(),
                    _buildPatienAvatar(avatar),
                    FExpanded(
                      child: FObx(
                        () => FColumn(
                          children: [
                            FRow(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildPatientNameTemplate(),
                                _buildRegistrationStatusTemplate(),
                              ],
                            ),
                            _buildIntervalWidget(6),
                            _buildPhoneTemplate(),
                            _buildIntervalWidget(3),
                            _buildIdCard(),
                            _buildIntervalWidget(3),
                            _buildPatientAgeTemplate(),
                            _buildIntervalWidget(3),
                            _buildHospitalBelonging(),
                            _buildIntervalWidget(6),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                FContainer(
                  margin: dividerLength,
                  child: FDivider(
                    color: Color.fromRGBO(216, 216, 216, 1),
                    thickness: 0.5,
                  ),
                ),
                FRow(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    if (widget.patientInfo!.isReferral! && isPatientTab)
                      FContainer(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(
                            4,
                          ),
                          color: Colors.red,
                        ),
                        child: FText(
                          i18nBook.remedical.transferredOut.t,
                          style: TextStyle(
                            color: Colors.white,
                          ),
                        ),
                      )
                    else if (!isPatientTab)
                      FRow(
                        children: [
                          FText(
                            widget.patientInfo!.outUserName ?? '',
                            style: TextStyle(
                              color: lightColorWhenActive,
                              fontSize: FFontSizes.H5,
                            ),
                          ),
                          FSizedBox(
                            width: 5,
                          ),
                          FIcon(
                            FIcons.fis_arrow_right,
                            size: 25,
                            color: lightColorWhenActive,
                          ),
                          FSizedBox(
                            width: 5,
                          ),
                          FText(
                            widget.patientInfo!.inUserName ?? '',
                            style: TextStyle(
                              color: lightColorWhenActive,
                              fontSize: FFontSizes.H5,
                            ),
                          ),
                        ],
                      )
                    else
                      FContainer(),
                    _buildButtonList(),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );

    return child;
  }

  FWidget _buildButtonList() {
    /// 当前数据的病人Code
    var patientCode = widget.patientInfo!.patientCode;

    return FRow(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        FRow(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            if (isPatientTab)
              FGestureDetector(
                businessParent: this.widget,
                name: "deletePatient:$patientCode",
                onTap: () => controller.patientInfoController
                    .deletePatient(patientCode, this.widget),
                child: FMaterialTooltip(
                  preferBelow: false,
                  padding: EdgeInsets.all(5),
                  message: i18nBook.common.delete.t,
                  child: FIcon(
                    Icons.delete_outline_rounded,
                    size: 25,
                    color: lightColorWhenActive,
                  ),
                ),
              ),
            isShowReferral
                ? FSizedBox(
                    width: 20,
                  )
                : FContainer(),
            isShowReferral && isPatientTab
                ? FGestureDetector(
                    businessParent: this.widget,
                    name: "openCreatecheckPage:$patientCode",
                    onTap: () {
                      controller.inspectionRecordsController
                          .openCreatecheckPage(
                        patientCode,
                      );
                    },
                    child: FMaterialTooltip(
                      preferBelow: false,
                      padding: EdgeInsets.all(5),
                      message: i18nBook.remedical.createCheck.t,
                      child: FIcon(
                        Icons.library_add,
                        size: 20,
                        color: lightColorWhenActive,
                      ),
                    ),
                  ) as FWidget
                : FContainer(),
            isShowReferral
                ? FContainer()
                : FRow(
                    children: [
                      FSizedBox(
                        width: 20,
                      ),
                      FGestureDetector(
                        businessParent: this.widget,
                        name: "AssociatPatient:$patientCode",
                        onTap: () {
                          controller.state.patient = widget.patientInfo;
                          router.dialog(
                            () => AssociatPatient(
                              patientCode,
                            ),
                          );
                        },
                        child: FMaterialTooltip(
                            preferBelow: false,
                            padding: EdgeInsets.all(5),
                            message: i18nBook.remedical.associateUserTip.t,
                            child: FContainer(
                              width: 35,
                              child: FStack(
                                children: [
                                  FIcon(
                                    FIcons.associated_patient,
                                    size: 20,
                                    color: lightColorWhenActive,
                                  ),
                                  FPositioned(
                                    left: 15,
                                    bottom: 6,
                                    child: FIcon(
                                      Icons.help,
                                      size: 14,
                                      color: lightColorWhenActive,
                                    ),
                                  ),
                                ],
                              ),
                            )),
                      ),
                    ],
                  ),
            // isShowReferral
            //     ? FRow(
            //         children: [
            //           FSizedBox(
            //             width: 20,
            //           ),
            //           FGestureDetector(
            //             businessParent: this.widget,
            //             name: "openReferDoctorDiaLog:$patientCode",
            //             onTap: () => controller
            //                 .openReferDoctorDiaLog(widget.patientInfo!),
            //             child: FMaterialTooltip(
            //               preferBelow: false,
            //               padding: EdgeInsets.all(5),
            //               message: i18nBook.remedical.transfer.t,
            //               child: FIcon(
            //                 FIcons.refer_hospital,
            //                 size: 20,
            //                 color: lightColorWhenActive,
            //               ),
            //             ),
            //           ),
            //         ],
            //       )
            //     : FContainer(),
            FSizedBox(
              width: 15,
            ),
          ],
        ),
        FSizedBox(
          height: 3,
        ),
      ],
    );
  }

  FWidget _buildPatienAvatar(String avatar) {
    return FContainer(
      width: 60,
      height: 60,
      margin: EdgeInsets.only(
        right: 15,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(4),
        ),
        color: isActive ? Colors.white : FTheme.ins.colorScheme.primary,
      ),
      child: FCenter(
        child: widget.patientInfo!.headImgUrl == '' ||
                widget.patientInfo!.headImgUrl == null
            ? FText(
                avatar,
                style: TextStyle(
                  fontSize: 22,
                  color:
                      isActive ? FTheme.ins.colorScheme.primary : Colors.white,
                ),
              )
            : FClipRRect(
                borderRadius: BorderRadius.circular(
                  4,
                ),
                child: FConstrainedBox(
                  constraints: BoxConstraints.expand(), // 自适应屏幕
                  child: FImage.network(
                    widget.patientInfo!.headImgUrl!,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
      ),
    );
  }

  ///病人姓名
  FWidget _buildPatientNameTemplate() {
    var name = widget.patientInfo!.name!;
    if (name.isEmpty) {
      name = i18nBook.remedical.notFill.t;
    }
    return FConstrainedBox(
      constraints: BoxConstraints(maxWidth: 130),
      child: FText(
        name,
        style: TextStyle(
          color: lightColorWhenActive,
          fontSize: FFontSizes.H5,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  /// 病人年龄
  FWidget _buildPatientAgeTemplate() {
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 75 : 100,
          child: FText(
            i18nBook.remedical.age.t,
            style: TextStyle(
              color: lightColorWhenActive,
              fontWeight: isActive ? FontWeight.normal : FontWeight.bold,
            ),
          ),
        ),
        // 年龄变更
        AgeText(
          ageUnits: widget.patientInfo?.ageUnits,
          ageDay: widget.patientInfo?.ageDay,
          ageMonth: widget.patientInfo?.ageMonth,
          ageWeek: widget.patientInfo?.ageWeek,
          ageYear: widget.patientInfo?.ageYear,
          style: TextStyle(
            color: lightColorWhenActive,
          ),
        ),
      ],
    );
  }

  FWidget _buildIntervalWidget(double heightNumber) {
    return FSizedBox(
      height: heightNumber,
    );
  }

  FWidget _buildRegistrationStatusTemplate() {
    return FContainer(
      alignment: Alignment.centerRight,
      width: 120,
      child: isPatientTab
          ? isShowReferral
              ? StatusLabel(
                  title: i18nBook.remedical.registered.t,
                  color: Color.fromRGBO(124, 182, 90, 1),
                )
              : StatusLabel(
                  title: i18nBook.remedical.notRegistered.t,
                  color: Color.fromRGBO(242, 75, 71, 1),
                )
          : widget.patientInfo!.isReferral!
              ? StatusLabel(
                  title: i18nBook.remedical.transferredOut.t,
                  color: Color.fromRGBO(242, 75, 71, 1),
                )
              : FSizedBox(),
    );
  }

  ///手机号
  FWidget _buildPhoneTemplate() {
    var phone = widget.patientInfo!.phone!;
    if (phone.isEmpty) {
      phone = i18nBook.remedical.notFill.t;
    }
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 75 : 100,
          child: FText(
            controller.state.patientType == OrganizationPatientTypeEnum.Person
                ? i18nBook.common.mobileNumber.t
                : i18nBook.remedical.ownerPhone.t,
            style: TextStyle(
              color: lightColorWhenActive,
              fontWeight: isActive ? FontWeight.normal : FontWeight.bold,
            ),
          ),
        ),
        FText(
          phone,
          style: TextStyle(
            color: lightColorWhenActive,
          ),
        )
      ],
    );
  }

  ///身份证号码
  FWidget _buildIdCard() {
    var patientInfoId = widget.patientInfo?.identityCard;
    var id = '';
    if (patientInfoId == null || patientInfoId.isEmpty) {
      id = i18nBook.remedical.notFill.t;
    } else {
      id = widget.patientInfo?.identityCard ?? '';
    }
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 75 : 100,
          child: controller.state.patientType ==
                  OrganizationPatientTypeEnum.Person
              ? FText(
                  i18nBook.remedical.idCard.t,
                  style: TextStyle(
                    color: lightColorWhenActive,
                    fontWeight: isActive ? FontWeight.normal : FontWeight.bold,
                  ),
                )
              : FText(
                  i18nBook.remedical.petId.t,
                  style: TextStyle(
                    color: lightColorWhenActive,
                    fontWeight: isActive ? FontWeight.normal : FontWeight.bold,
                  ),
                ),
        ),
        FText(
          id,
          style: TextStyle(
            color: lightColorWhenActive,
          ),
        )
      ],
    );
  }

  /// 所属医院
  FWidget _buildHospitalBelonging() {
    String hospitalBelonging = widget.patientInfo?.organizationName ?? '';
    return FRow(
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 75 : 100,
          child: FText(
            i18nBook.user.OrganizationLocated.t,
            style: TextStyle(
              color: lightColorWhenActive,
              fontWeight: isActive ? FontWeight.normal : FontWeight.bold,
            ),
          ),
        ),
        FExpanded(
          child: FTextTooltip(
            padding: EdgeInsets.all(5),
            message: hospitalBelonging,
            child: FText(
              hospitalBelonging,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: lightColorWhenActive,
              ),
            ),
          ),
        )
      ],
    );
  }

  _buildCheckBox() {
    return FContainer(
      padding: EdgeInsets.fromLTRB(0, 0, 5, 5),
      child: FObx(
        () => widget.patientInfo!.exportMode
            ? FRectangleCheckbox(
                value: false,
                isCheck: widget.patientInfo!.isChecked,
                onChange: _onCheckBoxChanged,
                borderColor:
                    controller.state.selectPatientCardIndex == widget.index
                        ? Colors.white
                        : Color.fromRGBO(141, 141, 141, 1),
              )
            : FContainer(),
      ),
    );
  }

  void _onCheckBoxChanged(dynamic value, bool? isCheck) {
    widget.patientInfo!.isChecked = isCheck!;
    controller.state.updateSelectAllState();
  }
}
