import 'package:fis_i18n/i18n.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/architecture/states/states.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/widgets/speech_input.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/index.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/multi_select_dialog.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/patient_datetime.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_theme/theme.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class AppointmentInformation extends FStatelessWidget implements FPage {
  AppointmentInformation(this.width, {this.isEmergency = false});
  final double width;
  final controller = Get.find<AppointmentConsultationController>();
  static const C_REMOVE_EXTRA_MARGIN = 60.0;
  static const C_DOUBLE_MUTIPLE = 2.0;
  final bool isEmergency;
  late final state = controller.state;
  @override
  String get pageName => 'AppointmentInformation';

  int _pageIndex = 1;
  int _expertPageIndex = 1;
  String _keyword = '';
  String _expertKeyword = '';

  /// 表单流式布局
  static FWidget buildFormLayout(
    double width,
    List<FWidget> itemWidget,
  ) {
    return FConfigureLayoutStyle(
      width: width,
      child: FWrap(
        children: itemWidget,
        runSpacing: 8,
      ),
    );
  }

  @override
  FWidget build(BuildContext context) {
    return buildAppointmentInfo(context);
  }

  /// 预约信息
  FWidget buildAppointmentInfo(BuildContext context) {
    return FObx(
      () {
        return buildFormLayout(
          width,
          [
            ...state.appointmentKeyList.map((e) {
              switch (e.key) {
                case 'Device':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildConsultationEquipment(),
                  );
                case 'ConsultationTime':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildConsultationTime(
                      context,
                    ),
                  );
                case 'ScanUser':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildScanDoctor(),
                  );
                case 'Diseases':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildDiseaseName(),
                  );
                case 'ScanPosition':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildExamineSite(),
                  );
                case 'ExpertOrganization':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildConsultationInstitutions(),
                  );
                case 'Expert':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildCompetentExpert(),
                  );

                case 'ApplyUser':
                  if (controller.state.isApplyUserField)
                    return FConfigureLayout(
                      title: e.label,
                      isRequired: e.required,
                      widget: _buildApplicant(),
                    );
                  else
                    return FSizedBox();
                case 'ApplyOrganization':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildApplicantOrg(),
                  );
                case 'Operator':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildOperator(),
                  );
                case 'PrimaryDiagnosis':
                  return FConfigureLayout(
                    title: e.label,
                    isRequired: e.required,
                    widget: _buildPreliminaryDiagnosis(),
                    proportion: C_DOUBLE_MUTIPLE,
                  );
                default:
                  return FSizedBox();
              }
            }).toList()
          ],
        );
      },
    );
  }

  /// 初步诊断
  FWidget _buildPreliminaryDiagnosis() {
    return FExpanded(
      child: FContainer(
        margin: EdgeInsets.only(top: 5),
        child: FObx(() {
          final textEditingController = TextEditingController(
            text: state.appointmentInformation.preliminaryDiagnosis,
          );
          return FTextField(
            maxLines: 3,
            controller: textEditingController,
            onChanged: (val) =>
                state.appointmentInformation.preliminaryDiagnosis = val,
            decoration: InputDecoration(
              hintStyle: const TextStyle(
                fontSize: 16,
              ),
              fillColor: Colors.white.withOpacity(0.5),
              enabledBorder: const OutlineInputBorder(
                borderSide: BorderSide(
                  color: Color.fromRGBO(230, 230, 230, 1),
                  style: BorderStyle.solid,
                ),
              ),
              suffixIcon: ServerConfigManager.isASROn
                  ? FIconButton(
                      businessParent: this,
                      name: 'audio recod',
                      icon: FIcon(
                        Icons.mic,
                        color: FTheme.ins.colorScheme.primary,
                      ),
                      onPressed: () async {
                        await router.dialog(
                          () => SpeechInput(
                            null,
                            textEditingController: textEditingController,
                            onSubmit: (v) {
                              state.appointmentInformation
                                  .preliminaryDiagnosis = v;
                            },
                          ),
                          dismissible: false,
                        );
                      },
                    )
                  : null,
              focusedBorder: const OutlineInputBorder(
                borderSide: BorderSide(
                  width: 0.5,
                  style: BorderStyle.solid,
                ),
              ),
              filled: true,
            ),
          );
        }),
      ),
    );
  }

  /// 会诊设备
  FWidget _buildConsultationEquipment() {
    FWidget select;
    if (isEmergency) {
      select = FConfigureInput(
        textController: TextEditingController(
          text: state.deviceList
              .firstWhereOrNull(
                  (element) => element.code == state.selectedDeviceCode)
              ?.name,
        ),
        enabled: false,
      );
      return select;
    } else {
      select = FContainer(
        decoration: BoxDecoration(
          border: Border.all(
            color: Color.fromRGBO(230, 230, 230, 1),
          ),
          borderRadius: BorderRadius.circular(4.0),
        ),
        child: FSuggesionInput<FSelectModel>(
          inputFieldConfiguration: FSuggesionInputFieldConfiguration(
            focusNode: controller.deviceFocusNode,
            decoration: FRimlessInput.buildDecoration(
              height: 38,
              borderColor: Color.fromRGBO(230, 230, 230, 1),
              hintText: i18nBook
                  .realTimeConsultation.pleaseSelectConsultationEquipment.t,
              hintSize: 16,
              contentSize: 18,
            ),
            maxLength: 100,
            controller: controller.deviceInputController,
            onChanged: (val) {
              _pageIndex = 1;
              _keyword = val;
            },
          ),
          optionItemBuilder: (_, data) {
            return FListTile(
              title: FText(
                (data.code.isEmpty && data.name.isEmpty)
                    ? i18nBook.college.loadMore.t
                    : data.name,
                style: const TextStyle(
                  color: Colors.grey,
                  fontSize: FInput.hintSize,
                ),
              ),
            );
          },
          optionItemsFetcher: (pattern) async {
            if (pattern.isEmpty) {
              controller.deviceInputController.text = '';
              state.selectedDeviceCode = '';
              state.appointmentInformation.appointmentDevice = '';
            }
            return await controller.getPersonDeviceDropdownListAsync(
                keyWord: pattern, pageIndex: _pageIndex);
          },
          onLoadMore: (pattern) async {
            _pageIndex++;
            return await controller.getPersonDeviceDropdownListAsync(
              keyWord: _keyword,
              pageIndex: _pageIndex,
              isloadMore: true,
            );
          },
          onOptionSelected: (data) async {
            if (data.code.isEmpty && data.name.isEmpty) {
              _pageIndex++;
              await controller.getPersonDeviceDropdownListAsync(
                keyWord: _keyword,
                pageIndex: _pageIndex,
                isloadMore: true,
              );
              FocusScope.of(Get.context!)
                  .requestFocus(controller.deviceFocusNode);
            } else {
              controller.deviceInputController.text = data.name;
              state.selectedDeviceCode = data.code;
              state.appointmentInformation.appointmentDevice = data.code;
            }
          },
          noItemsFoundText:
              i18nBook.realTimeConsultation.pleaseSelectConsultationEquipment.t,
        ),
      );
    }
    return FExpanded(child: select);
  }

  /// 会诊时间
  FWidget _buildConsultationTime(BuildContext context) {
    if (isEmergency) {
      DateTime timeOfAppointment =
          controller.state.appointmentInformation.appointmentTime ??
              DateTime.now();
      var appointmentTime =
          DateFormat('yyyy-MM-dd').format(timeOfAppointment).toString();
      return FConfigureInput(
        textController: TextEditingController(
          text: appointmentTime,
        ),
        enabled: false,
      );
    }
    return PatientDateTime(
      buildKey: '',
      context: context,
    );
  }

  /// 扫查医生
  FWidget _buildScanDoctor() {
    if (isEmergency) {
      return FConfigureInput(
        textController: TextEditingController(
          text: state.scannDoctorList
              .firstWhereOrNull(
                  (element) => element.code == state.appointmentDocter)
              ?.name,
        ),
        enabled: false,
      );
    }
    final select = FObx(() {
      return FFromSelect(
        sourceList: state.scannDoctorList,
        hintText: i18nBook.realTimeConsultation.pleaseSelectScanningDoctor.t,
        value: state.appointmentDocter,
        onSelectChanged: (value, index) {
          state.appointmentInformation.appointmentDocter = value;
          state.appointmentDocter = value;
        },
      );
    });
    return FExpanded(child: select);
  }

  /// 疾病名称
  FWidget _buildDiseaseName() {
    return FExpanded(
      child: FBorderInput(
        contentSize: 16,
        maxLength: 20,
        width: 300,
        borderColor: const Color.fromRGBO(230, 230, 230, 1),
        height: 38,
        controller: TextEditingController(
          text: state.appointmentInformation.appointmentDiseaseName,
        ),
        onChanged: (value) {
          state.appointmentInformation.appointmentDiseaseName = value;
        },
      ),
    );
  }

  /// 检查部位
  FWidget _buildExamineSite() {
    final input = FObx(() {
      List<String> appointmentScanningPositionValueList = [];
      String appointmentScanningPositionValue = '';
      final appointmentInformation = state.appointmentInformation;
      state.appointmentInformation.appointmentScanningPosition
          ?.forEach((element) {
        appointmentScanningPositionValueList.add(controller.getLanguageValues(
          element,
        ));
      });
      appointmentScanningPositionValue =
          appointmentScanningPositionValueList.join(", ");
      state.scanPositionsString = appointmentScanningPositionValue;
      TextEditingController textController = TextEditingController(
        text: controller.state.scanPositionsString,
      );
      return FExpanded(
        child: FBorderInput(
          contentSize: 16,
          maxLength: 20,
          width: 300,
          borderColor: const Color.fromRGBO(230, 230, 230, 1),
          height: 38,
          controller: textController,
          readOnly: true,
          onTap: () {
            Get.dialog(
              FObx(() {
                final scanPositionsList = state.scanPositionsList;
                return FMultiSelectDialog(
                    selectList: scanPositionsList,
                    appointmentScanningPositionList:
                        appointmentInformation.appointmentScanningPosition,
                    onOKSelect: (value) {
                      appointmentInformation.appointmentScanningPosition =
                          value;
                      controller.state.scanPositionsString = value.join(", ");
                    });
              }),
            );
          },
          onChanged: (value) {
            state.appointmentInformation.appointmentDiseaseName = value;
          },
        ),
      );
    });

    return input;
  }

  /// 会诊机构
  FWidget _buildConsultationInstitutions() {
    if (isEmergency) {
      return FConfigureInput(
        textController: TextEditingController(
          text: state.consultationInstitution
              .firstWhereOrNull((element) =>
                  element.code == state.selectedconsultationInstitution)
              ?.name,
        ),
        enabled: false,
      );
    }
    final select = FObx(() {
      return FFromSelect(
        sourceList: state.consultationInstitution,
        hintText:
            i18nBook.realTimeConsultation.pleaseSelectConsultationInstitution.t,
        value: state.selectedconsultationInstitution,
        onSelectChanged: (value, index) {
          state.appointmentInformation.appointmentConsultationInstitution =
              value;
          state.selectedconsultationInstitution = value;
          controller.expertInputController.text = '';
          state.appointmentInformation.appointmentCompetentExpert = '';
          controller.findOrganizationExpertsAsync();
        },
      );
    });
    return FExpanded(child: select);
  }

  /// 会诊专家
  FWidget _buildCompetentExpert() {
    if (isEmergency) {
      return FConfigureInput(
        textController: TextEditingController(
          text: state.competentExperts
              .firstWhereOrNull((element) =>
                  element.code ==
                  state.appointmentInformation.appointmentCompetentExpert)
              ?.name,
        ),
        enabled: false,
      );
    }
    final select = FObx(() {
      final appointmentInformation = state.appointmentInformation;
      final competentExperts = state.competentExperts;
      return FContainer(
        decoration: BoxDecoration(
          border: Border.all(
            color: Color.fromRGBO(230, 230, 230, 1),
          ),
          borderRadius: BorderRadius.circular(4.0),
        ),
        child: FSuggesionInput<FSelectModel>(
          inputFieldConfiguration: FSuggesionInputFieldConfiguration(
            focusNode: controller.expertFocusNode,
            decoration: FRimlessInput.buildDecoration(
              height: 38,
              borderColor: Color.fromRGBO(230, 230, 230, 1),
              hintText:
                  i18nBook.realTimeConsultation.pleaseSelectCompetentExpert.t,
              hintSize: 16,
              contentSize: 18,
            ),
            maxLength: 100,
            controller: controller.expertInputController,
            onChanged: (val) {
              _expertPageIndex = 1;
              _expertKeyword = val;
            },
          ),
          optionItemBuilder: (_, data) {
            return FListTile(
              title: FText(
                (data.code.isEmpty && data.name.isEmpty)
                    ? i18nBook.college.loadMore.t
                    : data.name,
                style: const TextStyle(
                  color: Colors.grey,
                  fontSize: FInput.hintSize,
                ),
              ),
            );
          },
          optionItemsFetcher: (pattern) async {
            if (pattern.isEmpty) {
              controller.expertInputController.text = '';
              appointmentInformation.appointmentCompetentExpert = '';
            }
            return await controller.findOrganizationExpertsAsync(
                keyword: pattern, pageIndex: _expertPageIndex);
          },
          onLoadMore: (pattern) async {
            _expertPageIndex++;
            return await controller.findOrganizationExpertsAsync(
              keyword: _expertKeyword,
              pageIndex: _expertPageIndex,
              isloadMore: true,
            );
          },
          onOptionSelected: (data) async {
            if (data.code.isEmpty && data.name.isEmpty) {
              _expertPageIndex++;
              await controller.findOrganizationExpertsAsync(
                keyword: _expertKeyword,
                pageIndex: _expertPageIndex,
                isloadMore: true,
              );
            } else {
              controller.expertInputController.text = data.name;
              appointmentInformation.appointmentCompetentExpert = data.code;
            }
          },
          noItemsFoundText:
              i18nBook.realTimeConsultation.pleaseSelectCompetentExpert.t,
        ),
      );
    });
    return FExpanded(child: select);
  }

  /// 申请人
  FWidget _buildApplicant() {
    final select = FObx(() {
      return FSelect<FSelectModel, String>(
        source: state.organizationAssistants,
        fontFamily: FTheme.ins.localeSetting.fontFamily,
        hintText: i18nBook.realTimeConsultation.pleaseSelectApplicant.t,
        value: state.appointmentInformation.appointmentApplicant,
        clearable: true,
        height: 36,
        optionLabelExtractor: (data) => data.name,
        optionValueExtractor: (data) => data.code,
        onSelectChanged: (value, index) {
          state.appointmentInformation.appointmentApplicant = value;
        },
      );
    });
    return FExpanded(child: select);
  }

  /// 申请机构
  FWidget _buildApplicantOrg() {
    return FExpanded(child: FText(Store.user.rootOrganizationName));
  }

  /// 申请机构
  FWidget _buildOperator() {
    return FExpanded(child: FText(Store.user.displayName));
  }
}
