import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/local_rtmp.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controller.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/index.dart';
import 'package:flyinsono/views/desktop/check_list_page_creation/bindings.dart';
import 'package:flyinsono/views/desktop/check_list_page_creation/controller.dart';
import 'package:flyinsono/views/desktop/check_list_page_creation/widgets/select_patient.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';

class CreateRecord extends FStatefulWidget implements FPage {
  @override
  String get pageName => "CreateRecord";

  @override
  FState<FStatefulWidget> createState() {
    return CreateRecordState();
  }
}

class CreateRecordState extends FState<CreateRecord> {
  final phoneController = TextEditingController();
  final nameController = TextEditingController();
  final ageController = TextEditingController();
  final languageManager = Get.find<ILanguageConfigManager>();
  final localRtmpManager = Get.find<ILocalRtmpManager>();
  final medicalHistoryController = TextEditingController();
  final examiningPhysicianController = TextEditingController();
  final birthDayController = TextEditingController();
  PatientInfo? _patientInfo;
  List<FSelectModel> get source => [
        FSelectModel(
          code: 'Male',
          name: languageManager.getExamLanguageValue("Male"),
        ),
        FSelectModel(
          code: 'Female',
          name: languageManager.getExamLanguageValue("Female"),
        ),
      ];
  String? selectedGender;

  @override
  FWidget build(BuildContext context) {
    final inputBorder = InputDecoration(
      // 设置四周边框的样式
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(
          color: Colors.grey[300]!,
          width: 1,
        ),
      ),
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(
          color: FTheme.ins.colorScheme.primary, // 焦点时边框颜色
          width: 1.0,
        ),
      ),
    );
    return FSimpleDialog(
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      isUseColumnLayout: false,
      contentPadding: EdgeInsets.all(15),
      onOk: () async {
        var name = nameController.text;
        var age = ageController.text;
        //必填校验
        if (name.isNullOrEmpty ||
            selectedGender.isNullOrEmpty ||
            age.isNullOrEmpty) {
          PromptBox.toast(i18nBook.user.requiredFieldsCannotBeEmpty.t);
          return;
        }
        _patientInfo?.name = nameController.text;
        _patientInfo?.sex = selectedGender;
        _patientInfo?.phone = phoneController.text;
        _patientInfo?.birthday = birthDayController.text;
        _patientInfo?.ageYear = ageController.text;
        _patientInfo?.medicalHistory = medicalHistoryController.text;
        _patientInfo?.examiningPhysician = examiningPhysicianController.text;
        var patientDatas = Get.find<IRemedicalManager>()
            .convertPatientInfoToPatientDatas(_patientInfo);
        var result = await localRtmpManager.createRecordInfo(
            _patientInfo?.patientCode ?? '', patientDatas);
        if (result) {
          router.back();
        } else {
          PromptBox.toast(i18nBook.remedical.addFailed.t);
        }
      },
      onCancel: () {
        router.back();
      },
      title: FText(
        i18nBook.remedical.createCheck.t,
        style: TextStyle(color: Colors.white),
      ),
      children: [
        FColumn(
          children: [
            FSizedBox(
              width: 680,
              height: 220,
              child: FGridView.count(
                crossAxisCount: 2,
                mainAxisSpacing: 15,
                childAspectRatio: 8.5,
                children: [
                  FTitleField(
                    i18nBook.common.fullName.t,
                    FBorderInput(
                      contentSize: 16,
                      maxLength: 20,
                      width: 300,
                      borderColor: const Color.fromRGBO(230, 230, 230, 1),
                      height: 38,
                      hintSize: 16,
                      readOnly: true,
                      enableInteractiveSelection: false,
                      controller: nameController,
                      onTap: () {
                        router.dialog(
                          () => CheckListSelectPatient(
                            selectPatient: (patientInfo) {
                              _patientInfo = patientInfo;
                              nameController.text = patientInfo.name ?? '';
                              ageController.text = patientInfo.ageYear ?? '';
                              FSelectModel? gender = source.firstWhereOrNull(
                                  (element) => element.code == patientInfo.sex);
                              if (gender != null) {
                                setState(() {
                                  selectedGender = gender.code;
                                });
                              }
                              birthDayController.text =
                                  patientInfo.birthday ?? '';
                              phoneController.text = patientInfo.phone ?? '';
                              examiningPhysicianController.text =
                                  patientInfo.examiningPhysician ?? '';
                              medicalHistoryController.text =
                                  patientInfo.medicalHistory ?? '';
                            },
                          ),
                          binding: CheckListPageCreationBinding(),
                        );
                        Get.find<ConsultationRecordViewController>()
                            .checkController
                            .searchPatient();
                      },
                    ),
                    isRequiredField: true,
                  ),
                  FTitleField(
                    i18nBook.remedical.age.t,
                    FTextField(
                      controller: ageController,
                      decoration: inputBorder,
                    ),
                    isRequiredField: true,
                  ),
                  FTitleField(
                    i18nBook.remedical.gender.t,
                    FSelect(
                      height: 40,
                      width: 210,
                      value: selectedGender,
                      hintText: i18nBook.common.Select.t,
                      source: source,
                      onSelectChanged: (value, index) {
                        selectedGender = value;
                      },
                      optionLabelExtractor: (FSelectModel data) {
                        return data.name;
                      },
                      optionValueExtractor: (FSelectModel data) {
                        return data.code;
                      },
                    ),
                    isRequiredField: true,
                  ),
                  FTitleField(
                    i18nBook.common.mobileNumber.t,
                    FTextField(
                      controller: phoneController,
                      decoration: inputBorder,
                    ),
                  ),
                  FTitleField(
                    i18nBook.common.dateOfBirth.t,
                    FBorderInput(
                      hintSize: 16,
                      height: 40,
                      width: 210,
                      contentSize: 16,
                      maxLength: 20,
                      onTap: () {
                        openSelectTime(context);
                      },
                      readOnly: true,
                      borderColor: const Color.fromRGBO(234, 234, 234, 1),
                      controller: birthDayController,
                      suffixIcon: FMaterial(
                        color: Colors.transparent,
                        child: FIconButton(
                          onPressed: () {
                            openSelectTime(context);
                          },
                          icon: const FIcon(
                            Icons.date_range_rounded,
                          ),
                          businessParent: widget,
                          name: '',
                        ),
                      ),
                      hintText: i18nBook.remedical.selectTime.t,
                    ),
                  ),
                  FTitleField(
                    i18nBook.remedical.checkDoctor.t,
                    FTextField(
                      controller: examiningPhysicianController,
                      decoration: inputBorder,
                    ),
                  ),
                ],
              ),
            ),
            FContainer(
              width: 680,
              height: 200,
              child: FTitleField(
                i18nBook.common.medicalHistory.t,
                FSizedBox(
                  height: 200,
                  width: 560,
                  child: FTextField(
                    maxLines: 6,
                    minLines: 6,
                    controller: medicalHistoryController,
                    decoration: inputBorder,
                  ),
                ),
                maxLargeFieldWidth: 590,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Future<void> openSelectTime(BuildContext context) async {
    var date = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        locale: i18nBook.locale,
        lastDate: DateTime(2050));
    if (date == null) return;
    birthDayController.text = DateFormat('yyyy-MM-dd').format(date);
  }
}
