import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.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/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/pages/consultation/controller.dart';
import 'package:flyinsono/pages/consultation/widgets/light_title.dart';
import 'package:flyinsono/pages/consultation/widgets/line_patient_data.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/multi_select_dialog.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/member_avatars.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/bottom_sheet.dart';
import 'package:get/get.dart';

import 'index.dart';
import 'widgets/update_patient_info.dart';
import 'widgets/update_patient_selected_info.dart';

class ConsultationDetailPage extends FisView<ConsultationDetailController>
    implements FPage {
  const ConsultationDetailPage({Key? key}) : super(key: key);
  @override
  FWidget build(BuildContext context) {
    final page = context.fResponsiveVoid(
      mobile: () => _MobileLayout(this),
      desktop: () => _DesktopLayout(this),
    );
    return page;
  }

  @override
  String get pageName => "consultation_detail";
}

class _MobileLayout extends FisView<ConsultationDetailController>
    implements FWidget {
  _MobileLayout(this.businessParent, {Key? key}) : super(key: key);
  final ScrollController _scrollController = ScrollController();
  final languageConfigManager = Get.find<ILanguageConfigManager>();
  bool get isEdit => controller.state.isEdit;
  bool get isEmergency => controller.state.consultationDetail.isEmergency;
  final consultationController = Get.find<MobileConsultationController>();

  ///父级节点
  final FPage businessParent;
  static const double _bttonButtonHeight = 50;
  late BuildContext _context;

  static const _textStyle = TextStyle(
    fontSize: FFontSizes.H5,
  );

  @override
  FWidget build(BuildContext context) {
    _context = context;
    return FScaffold(
      backgroundColor: Colors.grey[100],
      appBar: FAppBar(
        backgroundColor: FTheme.ins.colorScheme.primary,
        title: FText(
          i18nBook.realTimeConsultation.consultationDetail.t,
          style: TextStyle(
              fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
        ),
        actions: [
          FObx(() {
            var consultationDetail = controller.state.consultationDetail;
            if (consultationDetail.isEmergency &&
                consultationDetail.isImproveShow) {
              return FElevatedButton(
                child: FObx(() => FText(controller.state.isEdit
                    ? i18nBook.common.save.t
                    : i18nBook.common.edit.t)),
                onPressed: () {
                  if (!controller.state.isEdit) {
                    controller.state.isEdit = true;
                  } else {
                    var checkResult = _checkDataValid();
                    if (checkResult) {
                      controller.improveConsultationInfo();
                    } else {
                      PromptBox.toast(i18nBook
                          .realTimeConsultation.requiredItemsNotCompleted.t);
                    }
                  }
                },
                businessParent: businessParent,
                style: ButtonStyle(
                  elevation: MaterialStateProperty.resolveWith<double>(
                    (Set<MaterialState> states) {
                      return 0; // 默认阴影
                    },
                  ),
                ),
                name: 'edit',
              );
            } else {
              return FSizedBox();
            }
          })
        ],
        elevation: 0,
        centerTitle: true,
        leading: _buildLeading(),
      ),
      body: _buildConsultationDetailBody(context),
    );
  }

  ///会诊详情页内容
  FWidget _buildConsultationDetailBody(BuildContext context) {
    return FObx(() {
      bool isNeedStartButton =
          controller.state.consultationDetail.isInitiateShow;
      bool isShowJoin = controller.state.consultationDetail.isJoinInShow;
      bool isShowAgreeButton = controller.state.isShowAgreeButton;
      bool isShowAcceptInvitationButton =
          controller.state.isShowAcceptInvitationButton;
      bool isShowRefuseInvitationButton =
          controller.state.isShowRefuseInvitationButton;

      return FStack(
        children: [
          _buildConsultationDetail(
              (isNeedStartButton ||
                      isShowAgreeButton ||
                      isShowAcceptInvitationButton ||
                      isShowRefuseInvitationButton ||
                      isShowJoin) &&
                  !controller.state.isEdit,
              context),
          if (!controller.state.isEdit) ...[
            if (isNeedStartButton) ...[
              _buildBottomConsultationButton(
                i18nBook.realTimeConsultation.starttConsultation.t,
                controller.startConsultation,
              ),
            ] else if (isShowJoin) ...[
              _buildBottomConsultationButton(
                i18nBook.realTimeConsultation.joinConsultation.t,
                controller.joinConsultation,
              ),
            ],

            /// 同意或拒绝
            if (isShowAgreeButton) ...[
              FRow(
                children: [
                  FExpanded(
                    child: _buildBottomConsultationButton(
                      i18nBook.remedical.agree.t,
                      controller.agreeConsultation,
                    ),
                  ),
                  FExpanded(
                    child: _buildBottomConsultationButton(
                      i18nBook.remedical.refuse.t,
                      () {
                        FBottomSheet.showBottomSheet(
                          _context,
                          _buildTextArea(
                            (value) {
                              controller.state.refuseReason = value;
                            },
                          ),
                          () => controller
                              .refuseApplication(controller.state.refuseReason),
                        );
                      },
                      Colors.redAccent,
                    ),
                  ),
                ],
              ),
            ],

            /// 同意邀约 或拒绝邀约
            if (isShowAcceptInvitationButton &&
                isShowRefuseInvitationButton) ...[
              FRow(
                children: [
                  _buildAcceptInvitation(
                    i18nBook.realTimeConsultation.acceptInvitation.t,
                  ),
                  _buildRefuseInvitation(
                    i18nBook.realTimeConsultation.declineInvitation.t,
                  ),
                ],
              ),
            ],

            /// 已经同意邀约切换拒绝邀约
            if (!isShowAcceptInvitationButton &&
                isShowRefuseInvitationButton) ...[
              FRow(
                children: [
                  _buildRefuseInvitation(
                    i18nBook.realTimeConsultation.changeToDeclineInvitation.t,
                  ),
                ],
              ),
            ],

            /// 已经拒绝邀约切换同意邀约
            if (isShowAcceptInvitationButton &&
                !isShowRefuseInvitationButton) ...[
              FRow(
                children: [
                  _buildAcceptInvitation(
                    i18nBook.realTimeConsultation.changeToAcceptInvitation.t,
                  ),
                ],
              ),
            ],
          ],
        ],
      );
    });
  }

  /// 同意参加
  FWidget _buildAcceptInvitation(String agreeTitle) {
    return FExpanded(
      child: _buildBottomConsultationButton(
        agreeTitle,
        controller.agreeInvitation,
      ),
    );
  }

  /// 拒绝参加
  FWidget _buildRefuseInvitation(String refuseTitle) {
    return FExpanded(
      child: _buildBottomConsultationButton(
        refuseTitle,
        () {
          FBottomSheet.showBottomSheet(
            _context,
            _buildTextArea(
              (value) {
                controller.state.refuseInvitationReason = value;
              },
            ),
            () => controller.refuseInvitation(),
          );
        },
        Colors.redAccent,
      ),
    );
  }

  ///会诊详情
  FWidget _buildConsultationDetail(
      bool isNeedStartButton, BuildContext context) {
    return FObx(() {
      var patientInfo = controller.state.patientInfo;
      var consultationInfo = controller.state.consultationDetail;
      var gender =
          languageConfigManager.getExamLanguageValue(patientInfo.sex ?? '');
      var scanPosition = '';

      // var scanPosition = languageConfigManager
      //     .getApplicationLanguageValue(consultationInfo.scanPositions ?? '');
      String? ageInRecordCardList;
      List<String> scanPositions =
          []; // languageConfigManager.getApplicationLanguageValue(
      //     consultationInfo.scanPositions ?? '')),
      consultationInfo.scanPositions?.forEach((element) {
        scanPositions
            .add(languageConfigManager.getConsultationLanguageValue(element));
      });
      scanPosition = scanPositions.join(',');
      if (consultationController.state.consultationsRecordCardList.isNotEmpty) {
        ageInRecordCardList = consultationController
            .state
            .consultationsRecordCardList[
                consultationController.state.currentIndex]
            .age;
      }
      var age = patientInfo.ageYear.isNullOrEmpty
          ? ageInRecordCardList
          : patientInfo.ageYear;
      return FContainer(
        margin: EdgeInsets.only(
          bottom: isNeedStartButton ? (_bttonButtonHeight + FSpacings.XL) : 0,
        ),
        child: FAlwaysScrollListView(
          scrollController: _scrollController,
          child: QuickFWidget(ScrollConfiguration(
            behavior:
                ScrollConfiguration.of(context).copyWith(scrollbars: false),
            child: FListView(
              controller: _scrollController,
              shrinkWrap: true,
              children: [
                LightTitle(i18nBook.realTimeConsultation.patientInformation.t),
                //姓名
                if (isEdit) ...[
                  FSizedBox(height: 2),
                  SelectRow(
                    title: i18nBook.common.fullName.t,
                    hintText: '',
                    isRequired: true,
                    value: patientInfo.name ?? i18nBook.remedical.notFill.t,
                    fontSize: FFontSizes.H5,
                    onClick: () async {
                      controller.state.isAddPatient =
                          await controller.openSelectPatientPage((p) {
                        controller.state.patientInfo = p;
                      });
                    },
                  ),
                ] else ...[
                  LinePatientData(i18nBook.common.fullName.t, patientInfo.name),
                ],

                //手机号
                if (isEdit) ...[
                  FSizedBox(height: 2),
                  SelectRow(
                    title: i18nBook.common.mobileNumber.t,
                    isRequired: true,
                    hintText: '',
                    value: controller.state.patientInfo.phone ??
                        i18nBook.remedical.notFill.t,
                    fontSize: FFontSizes.H5,
                    onClick: () {
                      Get.to(
                        () => UpdatePatientInfo(
                          value: patientInfo.phone,
                          title: i18nBook.common.mobileNumber.t,
                          inputFormatters: [
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
                          ],
                          onSave: (v) {
                            if (GetUtils.isPhoneNumber(v)) {
                              controller.state.updatePatientPhone(v);
                              return true;
                            } else {
                              PromptBox.toast(
                                  i18nBook.errorCodes.errorCode6004.t);
                            }
                            return false;
                          },
                        ),
                      );
                    },
                  ),
                ] else ...[
                  LinePatientData(
                      i18nBook.common.mobileNumber.t, patientInfo.phone),
                ],

                FObx(() {
                  if (isEdit && controller.state.isAddPatient) {
                    return SelectRow(
                      title: i18nBook.remedical.age.t,
                      hintText: '',
                      value: patientInfo.ageYear.isNullOrEmpty
                          ? i18nBook.remedical.notFill.t
                          : patientInfo.ageYear,
                      fontSize: FFontSizes.H5,
                      onClick: () {
                        Get.to(
                          () => UpdatePatientInfo(
                            value: patientInfo.ageYear,
                            title: i18nBook.remedical.age.t,
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(
                                  RegExp(r'[0-9]')),
                            ],
                            onSave: (v) {
                              controller.state.updatePatientAge(v);
                              return true;
                            },
                          ),
                        );
                      },
                    );
                  } else {
                    return LinePatientData(
                      i18nBook.remedical.age.t,
                      age,
                    );
                  }
                }),

                //性别
                if (isEdit) ...[
                  FSizedBox(height: 2),
                  SelectRow(
                    title: i18nBook.remedical.gender.t,
                    hintText: '',
                    value: gender.isNullOrEmpty
                        ? i18nBook.remedical.notFill.t
                        : gender,
                    fontSize: FFontSizes.H5,
                    onClick: () {
                      Get.to(
                        () => UpdatePatientSelectedInfo(
                          items: controller.genderSelectedItems,
                          title: i18nBook.remedical.gender.t,
                          selectedItem: gender.isNullOrEmpty
                              ? null
                              : controller.genderSelectedItems
                                  .firstWhere(
                                      (element) => element.name == gender)
                                  .code,
                          onSelectChanged: (v) {
                            controller.state.updatePatientSex(v);
                          },
                        ),
                      );
                    },
                  ),
                ] else ...[
                  LinePatientData(
                    i18nBook.remedical.gender.t,
                    languageConfigManager
                        .getExamLanguageValue(patientInfo.sex ?? ''),
                  ),
                ],

                //病史
                if (isEdit) ...[
                  FSizedBox(height: 2),
                  SelectRow(
                    isRequired: true,
                    title: i18nBook.realTimeConsultation.pastMedicalHistory.t,
                    hintText: '',
                    value: patientInfo.anamnesis.isNullOrEmpty
                        ? i18nBook.remedical.notFill.t
                        : patientInfo.anamnesis,
                    fontSize: FFontSizes.H5,
                    onClick: () {
                      Get.to(
                        () => UpdatePatientInfo(
                          value: patientInfo.anamnesis,
                          title: i18nBook
                              .realTimeConsultation.pastMedicalHistory.t,
                          maxLines: 6,
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: FTheme.ins.colorScheme.primary,
                              width: 1.0,
                            ),
                          ),
                          onSave: (v) {
                            controller.state.updatePatientAnamnesis(v);
                            return true;
                          },
                        ),
                      );
                    },
                  ),
                ] else ...[
                  LinePatientData(
                      i18nBook.realTimeConsultation.pastMedicalHistory.t,
                      patientInfo.anamnesis),
                ],

                LightTitle(
                    i18nBook.realTimeConsultation.appointmentInformation.t),

                //会诊设备
                LinePatientData(
                    i18nBook.realTimeConsultation.consultationEquipment.t,
                    consultationInfo.displayName),
                //会诊时间
                LinePatientData(
                    i18nBook.realTimeConsultation.consultationHours.t,
                    consultationInfo.consultationTime == null
                        ? i18nBook.remedical.notFill.t
                        : controller.getConsultationTime(consultationInfo)),
                //检查部位
                if (isEdit) ...[
                  const FSizedBox(height: 2),
                  SelectRow(
                    title: i18nBook.realTimeConsultation.inspectionPosition.t,
                    hintText: '',
                    value: scanPosition.isNullOrEmpty
                        ? i18nBook.remedical.notFill.t
                        : scanPosition,
                    fontSize: FFontSizes.H5,
                    onClick: () {
                      Get.to(() => FMultiSelectDialog(
                            selectList: controller.scanPositions,
                            appointmentScanningPositionList:
                                consultationInfo.scanPositions,
                            onOKSelect: (value) {
                              controller.state.updateScanPosition(value);
                            },
                          ));
                    },
                  ),
                ] else ...[
                  LinePatientData(
                      i18nBook.realTimeConsultation.inspectionPosition.t,
                      scanPositions.join(','))
                ],

                //疾病名称
                if (isEdit) ...[
                  FSizedBox(height: 2),
                  SelectRow(
                    title: i18nBook.realTimeConsultation.nameOfDisease.t,
                    value: consultationInfo.diseases.isNullOrEmpty
                        ? i18nBook.remedical.notFill.t
                        : consultationInfo.diseases,
                    fontSize: FFontSizes.H5,
                    onClick: () {
                      Get.to(
                        () => UpdatePatientInfo(
                          maxlength: 20,
                          value: consultationInfo.diseases,
                          title: i18nBook.realTimeConsultation.nameOfDisease.t,
                          onSave: (v) {
                            controller.state.updateDiseases(v);
                            return true;
                          },
                        ),
                      );
                    },
                  )
                ] else ...[
                  LinePatientData(i18nBook.realTimeConsultation.nameOfDisease.t,
                      consultationInfo.diseases),
                ],

                //会诊机构
                LinePatientData(
                    i18nBook.realTimeConsultation.consultationInstitution.t,
                    consultationInfo.expertOrganizationName),
                //会诊专家
                LinePatientData(
                    i18nBook.realTimeConsultation.competentExperts.t,
                    consultationInfo.expertUserName),
                //申请机构
                LinePatientData(
                    i18nBook.realTimeConsultation.applicantMechanism.t,
                    consultationInfo.applyOrganizationName),
                //申请人
                LinePatientData(i18nBook.realTimeConsultation.applicantpeople.t,
                    consultationInfo.applyUserName),
                //操作人
                LinePatientData(i18nBook.realTimeConsultation.operator.t,
                    consultationInfo.operateUserName),
                //扫查医生
                LinePatientData(i18nBook.realTimeConsultation.scanDoctor.t,
                    consultationInfo.scanUserName),
                //初步诊断
                if (isEdit) ...[
                  const FSizedBox(height: 2),
                  SelectRow(
                    hintText: '',
                    title: i18nBook.realTimeConsultation.preliminaryDiagnosis.t,
                    value: consultationInfo.primaryDiagnosis.isNullOrEmpty
                        ? i18nBook.remedical.notFill.t
                        : consultationInfo.primaryDiagnosis,
                    fontSize: FFontSizes.H5,
                    onClick: () {
                      Get.to(
                        () => UpdatePatientInfo(
                          maxlength: 400,
                          maxLines: 6,
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: FTheme.ins.colorScheme.primary,
                              width: 1.0,
                            ),
                          ),
                          value: consultationInfo.primaryDiagnosis,
                          title: i18nBook
                              .realTimeConsultation.preliminaryDiagnosis.t,
                          onSave: (v) {
                            controller.state.updatePrimaryDiagnosis(v);
                            return true;
                          },
                        ),
                      );
                    },
                  )
                ] else ...[
                  LinePatientData(
                      i18nBook.realTimeConsultation.preliminaryDiagnosis.t,
                      consultationInfo.primaryDiagnosis),
                ],

                //助理医师
                if (consultationInfo.assistantUserName != null &&
                    consultationInfo.assistantUserName!.isNotEmpty)
                  LinePatientData(
                      i18nBook.realTimeConsultation.assistantPhysician.t,
                      consultationInfo.assistantUserName),
                // 已申请/已撤回/已拒绝不显示会诊描述和参与人员
                if (controller
                    .isShowDescriptionAndParticipants(consultationInfo)) ...[
                  //会诊描述
                  if (isEdit) ...[
                    const FSizedBox(height: 2),
                    SelectRow(
                      hintText: '',
                      title: i18nBook
                          .realTimeConsultation.consultationDescription.t,
                      value: consultationInfo.description.isNullOrEmpty
                          ? i18nBook.remedical.notFill.t
                          : consultationInfo.description,
                      fontSize: FFontSizes.H5,
                      onClick: () {
                        Get.to(
                          () => UpdatePatientInfo(
                            maxlength: 400,
                            maxLines: 6,
                            border: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: FTheme.ins.colorScheme.primary,
                                width: 1.0,
                              ),
                            ),
                            value: consultationInfo.description,
                            title: i18nBook
                                .realTimeConsultation.consultationDescription.t,
                            onSave: (v) {
                              controller.state.updateDescription(v);
                              return true;
                            },
                          ),
                        );
                      },
                    )
                  ] else ...[
                    LinePatientData(
                        i18nBook.realTimeConsultation.consultationDescription.t,
                        consultationInfo.description),
                  ],

                  //会诊参与人员
                  if (consultationInfo.consultationMembers != null &&
                      consultationInfo.consultationMembers!.isNotEmpty)
                    _buildParticipants(),
                ],
                // 拒绝原因
                if (consultationInfo.consultationStatus ==
                    TransactionStatusEnum.Rejected)
                  LinePatientData(
                      i18nBook.realTimeConsultation.reasonsForRefusal.t,
                      consultationInfo.rejectReason),

                //_buildShowMoreText(),
              ],
            ),
          )),
        ),
      );
    });
  }

  ///会诊参与人员
  FWidget _buildParticipants() {
    return FObx(
      () {
        var consultationInfo = controller.state.consultationDetail;
        var consultationMembers = consultationInfo.consultationMembers ?? [];
        return FContainer(
          margin: EdgeInsets.only(top: 2),
          color: Colors.white,
          padding: EdgeInsets.symmetric(
              horizontal: FSpacings.XXL, vertical: FSpacings.M),
          child: FRow(
            children: [
              FText(
                i18nBook.realTimeConsultation.participants.t,
                style: _textStyle,
              ),
              FExpanded(child: FSizedBox()),
              if (consultationMembers.length == 0) ...[
                FText(
                  i18nBook.remedical.notFill.t,
                  style: _textStyle.copyWith(
                    color: Colors.grey[600],
                  ),
                ),
              ] else ...[
                FMemberAvatars(
                  members: consultationMembers,
                  maxCount: 5,
                  onlyShowFive: true,
                ),
              ],
            ],
          ),
        );
      },
    );
  }

  //返回键
  FWidget _buildLeading() {
    return FIconButton(
      name: "back",
      businessParent: this.businessParent,
      icon: FIcon(Icons.arrow_back_ios_new, size: 20, color: Colors.white),
      onPressed: () {
        Get.back();
      },
    );
  }

  FWidget _buildTextArea(ValueCallback onChanged) {
    return FContainer(
      margin: EdgeInsets.all(15),
      child: FTextField(
        maxLines: 3,
        onChanged: (val) => onChanged.call(val),
        decoration: InputDecoration(
          hintStyle: TextStyle(
            fontSize: 14,
            color: Color.fromRGBO(155, 155, 155, 1),
          ),
          hintText: i18nBook.common.pleaseEnter.t,
          fillColor: Colors.white.withOpacity(0.5),
          enabledBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              color: Color.fromRGBO(230, 230, 230, 1),
              style: BorderStyle.solid,
            ),
          ),
          focusedBorder: const OutlineInputBorder(
            borderSide: BorderSide(
              width: 0.5,
              style: BorderStyle.solid,
            ),
          ),
          filled: true,
        ),
      ),
    );
  }

  ///开始会诊按钮
  FWidget _buildBottomConsultationButton(
    String buttonTitle,
    Function onTap, [
    Color? backgroundColor,
  ]) {
    return FAlign(
      alignment: Alignment.bottomCenter,
      child: FGestureDetector(
        businessParent: this.businessParent,
        child: FContainer(
          margin: EdgeInsets.symmetric(
            vertical: FSpacings.M,
            horizontal: FSpacings.M,
          ),
          height: _bttonButtonHeight,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(8),
            ),
            color: backgroundColor ?? FTheme.ins.colorScheme.primary,
          ),
          child: FText(
            buttonTitle,
            style: _textStyle.copyWith(color: Colors.white),
          ),
        ),
        onTap: () => onTap.call(),
        name: 'Start Consultation',
      ),
    );
  }

  bool _checkDataValid() {
    var patientInfo = controller.state.patientInfo;
    if (patientInfo.name.isNullOrEmpty) {
      return false;
    }
    if (patientInfo.phone.isNullOrEmpty) {
      return false;
    }
    if (patientInfo.anamnesis.isNullOrEmpty) {
      return false;
    }
    return true;
  }
}

class _DesktopLayout extends FisView<ConsultationDetailController>
    implements FWidget {
  _DesktopLayout(this.businessParent, {Key? key}) : super(key: key);
  final FPage businessParent;

  /// TODO: implement body
  @override
  FWidget build(BuildContext context) {
    return FContainer();
  }
}
