import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.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/router/router.dart';
import 'package:flyinsono/managers/interfaces/appointment_consultation.dart';
import 'package:flyinsono/pages/schedule/calendar/utils/calendar_utils.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/view.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/real_time_consultation_controller.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/add_consultation_evaluation.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/add_visit.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/confirm_application.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/dynamic_button.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/member_avatars.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/mixture_layout.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/refuse_reason_page.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/third_part_refuse_page.dart';
import 'package:get/get.dart';

/// 预约会诊详情页面
class FAppointmentApplication<T extends RealTimeConsultationController>
    extends FisView<T> implements FPage {
  FAppointmentApplication({super.key});

  bool get isDialog => false;

  @override
  String get pageName => 'FAppointmentApplication';

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      child: FColumn(
        children: [
          FExpanded(
            child: FColumn(
              children: [
                FExpanded(
                  flex: 9,
                  child: _buildPatientInfoContainer(),
                ),
                FExpanded(
                  flex: 10,
                  child: _buildAppointmentInfoContainer(),
                ),
              ],
            ),
          ),
          FContainer(
            height: 55,
            child: _buildActionBar(),
          ),
        ],
      ),
    );
  }

  /// 构建操作栏
  FWidget _buildActionBar() {
    return FContainer(
      padding: const EdgeInsets.all(10),
      decoration: const BoxDecoration(
        border: Border(
          top: BorderSide(
            color: Color.fromRGBO(216, 216, 216, 1),
            width: 0.5,
          ),
        ),
      ),
      child: FObx(() {
        return FRow(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            /// 开始会诊
            if (controller.state.isShowStartConsultationButton)
              _buildTextButton(
                  i18nBook.realTimeConsultation.starttConsultation.t, () {
                if (isDialog) {
                  router.back();
                }
                controller.startConsultation();
              }),
            if (controller.state.isShowEnterConsultationButton)
              _buildTextButton(i18nBook.realTimeConsultation.joinConsultation.t,
                  () {
                if (isDialog) {
                  router.back();
                }
                controller.startConsultation(isJoin: true);
              }),
            //完善会诊信息
            if (controller.state.isImproveShow)
              _buildTextButton(
                i18nBook.common.completeInformation.t,
                () async {
                  await Get.dialog(
                    FAppointmentConsultationPage(
                      realTimeConsultationController: this.controller,
                      consultationDetail:
                          controller.state.consultationsRecordInfos,
                    ),
                  );
                },
              ),

            /// 撤回
            if (controller.state.isShowWithdrawButton)
              _buildTextButton(i18nBook.realTimeConsultation.withdraw.t,
                  () async {
                await controller.revokeConsultation();
              }),

            /// 修改
            if (controller.state.isShowModifyButton)
              _buildTextButton(i18nBook.common.modify.t, () async {
                var result = await Get.dialog(
                  FAppointmentConsultationPage(
                    consultationDetail:
                        controller.state.consultationsRecordInfos,
                    realTimeConsultationController: controller,
                  ),
                );
                bool isCancel = false;
                if (result != null && result['isCancel'] == true) {
                  isCancel = true;
                }
                if (isDialog && !isCancel) {
                  router.back();
                }
              }),

            /// 同意
            if (controller.state.isShowAgreeButton)
              _buildTextButton(i18nBook.remedical.agree.t, () async {
                var result = await Get.dialog(
                  ComfirmApplicationPage(
                    controller: controller,
                  ),
                );
                bool isCancel = false;
                if (result != null && result['isCancel'] == true) {
                  isCancel = true;
                }
                if (isDialog && !isCancel) {
                  router.back();
                }
              }),

            /// 拒绝
            if (controller.state.isShowRefuseButton)
              _buildTextButton(i18nBook.user.refuse.t, () async {
                var result = await Get.dialog(
                  RefuseReasonPage(
                    controller: controller,
                  ),
                );
                bool isCancel = false;
                if (result != null && result['isCancel'] == true) {
                  isCancel = true;
                }
                if (isDialog && !isCancel) {
                  router.back();
                }
              }),

            /// 接受邀请
            if (controller.state.isShowAcceptInvitationButton &&
                controller.state.isDefaultStatus)
              _buildTextButton(i18nBook.realTimeConsultation.acceptInvitation.t,
                  () async {
                controller.agreeInvitation();
                if (isDialog) {
                  router.back();
                }
              }),

            /// 拒绝邀请
            if (controller.state.isShowRefuseInvitationButton &&
                controller.state.isDefaultStatus)
              _buildTextButton(
                  i18nBook.realTimeConsultation.declineInvitation.t, () async {
                var result = await Get.dialog(
                  ThirdPartRefusePage(
                    controller: controller,
                  ),
                );
                bool isCancel = false;
                if (result != null && result['isCancel'] == true) {
                  isCancel = true;
                }
                if (isDialog && !isCancel) {
                  router.back();
                }
              }),

            /// 第三方已同意邀约，可切换至拒绝
            FObx(() {
              if (controller.state.isAgreeStatus) {
                return DynamicButton(
                  displayString:
                      i18nBook.realTimeConsultation.acceptedInvitation.t,
                  actionString:
                      i18nBook.realTimeConsultation.changeToDeclineInvitation.t,
                  onPressed: () async {
                    await Get.dialog(
                      ThirdPartRefusePage(
                        controller: controller,
                      ),
                    );
                  },
                );
              } else {
                return FSizedBox();
              }
            }),

            /// 第三方已拒绝邀约，可切换至同意
            FObx(() {
              if (controller.state.isRefuseStatus) {
                return DynamicButton(
                  displayString:
                      i18nBook.realTimeConsultation.declinedInvitation.t,
                  actionString:
                      i18nBook.realTimeConsultation.changeToAcceptInvitation.t,
                  onPressed: () => controller.agreeInvitation(),
                  displayColor: Colors.red,
                  actionColor: Colors.green,
                );
              } else {
                return FSizedBox();
              }
            }),

            /// 评价
            if (controller.state.isShowEvaluateButton)
              _buildTextButton(
                  i18nBook.realTimeConsultation.consultationEvaluation.t,
                  () async {
                Get.put(RealTimeConsultationController());
                var result = await Get.dialog(
                  AddConsultationEvaluationView(),
                );
                bool isCancel = false;
                if (result != null && result['isCancel'] == true) {
                  isCancel = true;
                }
                if (isDialog && !isCancel) {
                  router.back();
                }
              }),

            ///随访
            if (controller.state.isShowFollowUpButton)
              _buildTextButton(i18nBook.realTimeConsultation.followUp.t,
                  () async {
                Get.dialog(
                  AddFollowUpVisitView(
                    realTimeConsultationController: this.controller,
                  ),
                );
              }),

            /// 写报告
            if (controller.state.isShowWriteReportButton)
              _buildTextButton(
                i18nBook.remedical.writeReport.t,
                () async {
                  final appointmentConsultationManager =
                      Get.find<IAppointmentConsultation>();
                  appointmentConsultationManager.openReportEdit(
                    controller.state.currentConsultationCode,
                    controller.state.consultationsRecordInfos.patientCode ?? '',
                  );
                },
              ),
          ],
        );
      }),
    );
  }

  /// 构建会诊单容器
  FWidget _buildAppointmentInfoContainer() {
    return FColumn(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FContainer(
          width: double.infinity,
          decoration: const BoxDecoration(
            border: Border(
              top: BorderSide(
                color: Color.fromRGBO(216, 216, 216, 1),
                width: 0.5,
              ),
            ),
          ),
          padding: EdgeInsets.all(20),
          child: FText(
            i18nBook.realTimeConsultation.appointmentInformation.t,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
        ),
        FFlexible(
          child: FContainer(
            padding: EdgeInsets.only(left: 20, right: 20, bottom: 20),
            child: _buildAppointmentInfoContent(),
          ),
        ),
      ],
    );
  }

  /// 构建会诊单内容
  FWidget _buildAppointmentInfoContent() {
    return FObx(() {
      final consultationsRecordInfos =
          controller.state.consultationsRecordInfos;
      final consultationTime = _getConsultationTime(consultationsRecordInfos);

      /// 是否显示助理( 不为空且会诊已被接受) 【后端变更完】 assistantDoctorUserName
      final bool isShowAssistantDoctor = consultationsRecordInfos
                  .assistantDoctorUserName !=
              '' &&
          _isConsultationAccepted(consultationsRecordInfos.consultationStatus);

      /// 是否显示拒绝原因
      final bool isShowRejectReason =
          consultationsRecordInfos.rejectReason != null &&
              consultationsRecordInfos.rejectReason!.isNotEmpty;

      /// 是否显示会诊描述
      /// 【已申请、已撤回、已拒绝】不显示会诊描述
      final bool isShowConsultationDescription = ![
        TransactionStatusEnum.Applied,
        TransactionStatusEnum.Withdrawn,
        TransactionStatusEnum.Rejected
      ].contains(consultationsRecordInfos.consultationStatus);

      ///  是否显示参与人
      final bool isShowParticipatePerson =
          consultationsRecordInfos.consultationMembers != null &&
              consultationsRecordInfos.consultationMembers!.length > 0;
      List<String> scanPositions = [];
      consultationsRecordInfos.scanPositions?.forEach((elemet) => {
            scanPositions.add(controller.getLanguageValues(
              'consultation',
              elemet,
            ))
          });

      return FMixtureLayout(
        children: [
          _buildHalfRowElement(
              i18nBook.realTimeConsultation.consultationEquipment.t,
              consultationsRecordInfos.displayName),
          _buildHalfRowElement(
              i18nBook.realTimeConsultation.consultationHours.t,
              consultationTime),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.inspectionPosition.t,
            scanPositions.join(','),
          ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.nameOfDisease.t,
            consultationsRecordInfos.diseases,
          ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.consultationInstitution.t,
            consultationsRecordInfos.expertOrganizationName,
          ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.competentExperts.t,
            consultationsRecordInfos.expertUserName,
          ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.applicantMechanism.t,
            consultationsRecordInfos.applyOrganizationName,
          ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.applicantpeople.t,
            consultationsRecordInfos.applyUserName,
          ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.operator.t,
            consultationsRecordInfos.operateUserName,
          ),
          if (isShowAssistantDoctor)
            _buildHalfRowElement(
              i18nBook.realTimeConsultation.assistantPhysician.t,
              consultationsRecordInfos.assistantDoctorUserName,
            ),
          _buildHalfRowElement(
            i18nBook.realTimeConsultation.scanDoctor.t,
            consultationsRecordInfos.scanUserName,
          ),
          if (isShowParticipatePerson)
            _participatePerson(consultationsRecordInfos.consultationMembers!),
          _buildOneRowElement(
            i18nBook.realTimeConsultation.preliminaryDiagnosis.t,
            consultationsRecordInfos.primaryDiagnosis,
          ),
          if (isShowConsultationDescription)
            _buildOneRowElement(
              i18nBook.realTimeConsultation.consultationDescription.t,
              consultationsRecordInfos.description,
            ),
          if (isShowRejectReason)
            _buildHalfRowElement(
              i18nBook.realTimeConsultation.reasonsForRefusal.t,
              consultationsRecordInfos.rejectReason,
            ),
        ],
      );
    });
  }

  /// 小模块（占半行）
  MixtureLayoutElement _buildHalfRowElement(
    String title,
    String? value,
  ) {
    return HalfRowLayout(
      child: FContainer(
        margin: const EdgeInsets.only(
          bottom: 15,
        ),
        child: FRow(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FExpanded(
              flex: 1,
              child: FText(
                title,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            FExpanded(
              flex: 2,
              child: _buildValueText(value),
            )
          ],
        ),
      ),
    );
  }

  /// 大模块（占一行）
  MixtureLayoutElement _buildOneRowElement(
    String title,
    String? value,
  ) {
    return FullRowLayout(
      child: FContainer(
        margin: const EdgeInsets.only(
          bottom: 15,
        ),
        child: FRow(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FExpanded(
              flex: 1,
              child: FText(
                title,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            FExpanded(
              flex: 5,
              child: _buildValueText(value),
            )
          ],
        ),
      ),
    );
  }

  /// 构建病人信息容器
  FWidget _buildPatientInfoContainer() {
    return FContainer(
      margin: const EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 2),
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FText(
            i18nBook.remedical.patientDetail.t,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
          const FSizedBox(
            height: 20,
          ),
          FExpanded(child: _buildPatientInfoContent()),
        ],
      ),
    );
  }

  /// 构建病人信息内容
  FWidget _buildPatientInfoContent() {
    return FObx(() {
      final consultationsRecordInfos =
          controller.state.consultationsRecordInfos;
      final patientDatas = consultationsRecordInfos.patientDatas ?? [];
      Map<String, String> patientValues =
          controller.getPatientValue(patientDatas);
      return FMixtureLayout(
        children: [
          _buildHalfRowElement(
            i18nBook.common.fullName.t,
            consultationsRecordInfos.patientName,
          ),
          _buildHalfRowElement(
            i18nBook.common.mobileNumber.t,
            patientValues['Phone'],
          ),
          _buildHalfRowElement(
            i18nBook.remedical.age.t,
            controller.getAgeValue(
              patientValues['AgeUnits'] ?? '',
              patientValues['AgeYear'] ?? '',
              patientValues['AgeMonth'] ?? '',
              patientValues['AgeWeek'] ?? '',
              patientValues['AgeDay'] ?? '',
            ),
          ),
          _buildHalfRowElement(
            i18nBook.remedical.gender.t,
            controller.getLanguageValues(
              'exam',
              patientValues['Sex'] ?? i18nBook.remedical.notFill.t,
            ),
          ),
          _buildOneRowElement(
            i18nBook.realTimeConsultation.pastMedicalHistory.t,
            patientValues['Anamnesis'],
          ),
        ],
      );
    });
  }

  /// 构建按钮
  FWidget _buildTextButton(String textString, Function onPressed) {
    return FContainer(
      /// TODO:[Gavin] 多语言-UI-整合
      width: i18nBook.isCurrentChinese
          ? 100
          : i18nBook.isCurrentRussian
              ? 160
              : 130,
      margin: const EdgeInsets.only(right: 15),
      child: FOutlinedButton(
        onPressed: () => onPressed.call(),
        style: ButtonStyle(
          padding: MaterialStateProperty.all(
            const EdgeInsets.symmetric(
              vertical: 8,
            ),
          ),
        ),
        businessParent: this,
        name: textString,
        child: FCenter(
          child: FText(
            textString,
            style: const TextStyle(color: Colors.black),
          ),
        ),
      ),
    );
  }

  FWidget _buildValueText(
    String? value,
  ) {
    String valueText;
    if (value == null) {
      valueText = i18nBook.remedical.notFill.t;
    } else {
      valueText = value != '' ? value : i18nBook.remedical.notFill.t;
    }
    return FContainer(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      child: FText(
        valueText,
        style: const TextStyle(
          fontSize: 16,
          color: Colors.black87,
        ),
        overflow: TextOverflow.fade,
      ),
    );
  }

  /// 获取预约会诊时间
  String _getConsultationTime(ConsultationDetailDTO info) {
    //如果会诊申请没有通过，会诊状态是待审核或者已拒绝或者已撤回，则只显示日期，不显示具体时间
    if (info.consultationTime == null) return '';
    if (_isConsultationAccepted(info.consultationStatus)) {
      if (info.consultationTimeEnd == null) return '';
      return CalendarUtils.formatDateRangeWithYear(
          info.consultationTime!.toLocal(),
          info.consultationTimeEnd!.toLocal());
    } else {
      return CalendarUtils.formatDate(
          CalendarUtils.getDay(info.consultationTime!.toLocal()));
    }
  }

  /// 会诊是否被接受
  bool _isConsultationAccepted(TransactionStatusEnum e) {
    //会诊状态
    List<TransactionStatusEnum> consultationStatus = [
      TransactionStatusEnum.Applied,
      TransactionStatusEnum.Rejected,
      TransactionStatusEnum.Withdrawn,
    ];
    return !consultationStatus.any((element) => element == e);
  }

  /// 构建参与人组件
  MixtureLayoutElement _participatePerson(
      List<ConsultationMemberDTO> consultationMembers) {
    return FullRowLayout(
      child: FContainer(
        margin: EdgeInsets.only(bottom: 15),
        child: FRow(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FExpanded(
              flex: 1,
              child: FText(
                i18nBook.realTimeConsultation.participants.t,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
            ),
            FExpanded(
              flex: 5,
              child: FContainer(
                margin: EdgeInsets.symmetric(horizontal: 10),
                child: FMemberAvatars(
                  members: consultationMembers,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 预约会诊详情弹窗
class FAppointmentApplicationDialog
    extends FAppointmentApplication<RealTimeConsultationDialogController> {
  @override
  bool get isDialog => true;
}
