import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/schedule/calendar/utils/calendar_utils.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/index.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/appointment_information.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/patient_information.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/real_time_consultation_controller.dart';
import 'package:get/get.dart';
import 'package:fis_ui/index.dart';

class FAppointmentConsultationPage extends FStatefulWidget {
  final ConsultationDetailDTO? consultationDetail;
  final RealTimeConsultationController realTimeConsultationController;
  const FAppointmentConsultationPage({
    Key? key,
    this.consultationDetail,
    required this.realTimeConsultationController,
  }) : super(key: key);

  @override
  FState<FAppointmentConsultationPage> createState() =>
      _FAppointmentConsultationPageState();
}

class _FAppointmentConsultationPageState
    extends FState<FAppointmentConsultationPage> {
  /// 是否是编辑状态
  bool isEdit = false;
  late AppointmentConsultationController controller;
  ConsultationDetailDTO? get consultationDetail => widget.consultationDetail;

  @override
  void initState() {
    super.initState();
    controller = Get.put(AppointmentConsultationController(
      realTimeConsultationController: widget.realTimeConsultationController,
    ));
    if (consultationDetail != null) {
      /// 初始化病人信息
      _initPatientInfos();

      /// 初始化预约信息
      _initAppointmentInformations();

      if (consultationDetail!.isEmergency) {
        controller.state.selectedDeviceCode = consultationDetail!.deviceCode;
        controller.state.appointmentInformation.appointmentDocter =
            consultationDetail!.operateUserCode;
      }

      /// 初始化会诊专家
      controller.expertInputController.text = controller
              .state.appointmentInformation.appointmentCompetentExpertName ??
          '';

      /// 初始化会诊设备
      controller.deviceInputController.text =
          controller.state.appointmentInformation.appointmentDeviceName ?? '';

      /// 编辑的时候部分会诊专家下拉数据需要显示出来
      controller.findOrganizationExpertsAsync();
      isEdit = true;
    } else {
      /// 新建时候默认填充当前时间
      controller.state.appointmentInformation.appointmentTime =
          CalendarUtils.getDay(DateTime.now());
    }
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      title: FText(
        (consultationDetail != null && consultationDetail!.isEmergency)
            ? i18nBook.common.completeInformation.t
            : i18nBook.realTimeConsultation.applyForAppointment.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.submit.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      onOk: () {
        if (isEdit) {
          if (consultationDetail != null && consultationDetail!.isEmergency) {
            controller.improveConsultationInfo();
          } else {
            controller.updateConsultationAsync();
          }
        } else {
          controller.createNewConsultationAsync();
        }
      },
      onCancel: () {
        router.back(result: {'isCancel': true});
      },
      children: [
        FContainer(
          /// TODO:[Gavin] 多语言-UI-整合
          width: i18nBook.isCurrentChinese ? 900 : 1200,
          child: FColumn(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FSizedBox(
                height: 10,
              ),
              _buildTitle(i18nBook.remedical.patientDetail.t),
              PatientInformation(
                !isEdit ||
                    (widget.consultationDetail != null &&
                        widget.consultationDetail!.isEmergency),

                /// TODO:[Gavin] 多语言-UI-整合
                i18nBook.isCurrentChinese ? 450 : 600,
              ),
              FSizedBox(
                height: 15,
              ),
              _buildLineDesign(),
              _buildTitle(
                  i18nBook.realTimeConsultation.appointmentInformation.t),
              AppointmentInformation(
                /// TODO:[Gavin] 多语言-UI-整合
                i18nBook.isCurrentChinese ? 450 : 600,
                isEmergency: consultationDetail?.isEmergency ?? false,
              ),
              FSizedBox(
                height: 5,
              ),
            ],
          ),
        ),
      ],
    );
  }

  FWidget _buildTitle(String title) {
    return FContainer(
      margin: EdgeInsets.only(left: 35, bottom: 15),
      child: FText(
        title,
        style: const TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  /// 分隔线
  FWidget _buildLineDesign() {
    return const FDivider();
  }

  /// 去除空字符串
  dynamic _emptyReturnNull(dynamic value) {
    if (value == null || (value is String && value.isEmpty)) {
      return null;
    }
    return value;
  }

  /// 病人信息初始化
  void _initPatientInfos() {
    final PatientInfo currentPatient = controller.state.currentPatient;
    final ConsultationDetailDTO consultationDetail =
        widget.consultationDetail ?? ConsultationDetailDTO();
    final List<DataItemDTO> patientDatas =
        consultationDetail.patientDatas ?? [];
    currentPatient.patientCode = consultationDetail.patientCode ?? '';
    for (DataItemDTO i in patientDatas) {
      if (i.key == 'Name') {
        currentPatient.name = i.value;
      }
      controller.patient[i.key ?? ''] = i.value ?? '';

      if (i.key == 'AgeUnits') {
        currentPatient.ageUnits = i.value ?? '';
      }
      if (i.key == 'AgeYear') {
        currentPatient.ageYear = i.value ?? '';
      }
      if (i.key == 'AgeMonth') {
        currentPatient.ageMonth = i.value ?? '';
      }
      if (i.key == 'AgeWeek') {
        currentPatient.ageWeek = i.value ?? '';
      }
      if (i.key == 'AgeDay') {
        currentPatient.ageDay = i.value ?? '';
      }
    }
    controller.state.isAddPatient = false;
  }

  /// 预约信息初始化
  void _initAppointmentInformations() {
    final AppointmentInformations appointmentInformation =
        controller.state.appointmentInformation;
    final ConsultationDetailDTO consultationDetail =
        widget.consultationDetail ?? ConsultationDetailDTO();

    appointmentInformation.appointmentApplicant =
        consultationDetail.applyUserCode; // 申请人
    appointmentInformation.appointmentDocter = _emptyReturnNull(
      consultationDetail.scanUserCode,
    ); // 扫查医生
    appointmentInformation.appointmentDevice = _emptyReturnNull(
      consultationDetail.deviceCode,
    ); // 会诊设备
    appointmentInformation.appointmentDeviceName = _emptyReturnNull(
      consultationDetail.deviceName,
    ); // 会诊设备名称
    appointmentInformation.appointmentScanningPosition = _emptyReturnNull(
      consultationDetail.scanPositions,
    ); // 检查部位
    appointmentInformation.appointmentConsultationInstitution =
        _emptyReturnNull(
      consultationDetail.expertOrganizationCode,
    ); // 会诊机构
    appointmentInformation.appointmentCompetentExpert = _emptyReturnNull(
      consultationDetail.expertUserCode,
    ); // 主管专家
    appointmentInformation.appointmentCompetentExpertName = _emptyReturnNull(
      consultationDetail.expertUserName,
    ); // 主管专家名字
    appointmentInformation.appointmentDiseaseName =
        consultationDetail.diseases; // 疾病名称
    appointmentInformation.preliminaryDiagnosis =
        consultationDetail.primaryDiagnosis; // 初步诊断
    appointmentInformation.appointmentTime =
        consultationDetail.consultationTime; // 会诊时间
  }
}
