import 'dart:convert';

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:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/entities/consultation_server_config.dart';
import 'package:flyinsono/managers/interfaces/entities/consultation_server_config.dart'
    as p;
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/pages/consultation/widgets/mobile_emergency_config.dart';
import 'package:flyinsono/pages/element_static.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/index.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/select_patient_dialog.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/controller/real_time_consultation_controller.dart';
import 'package:get/get.dart';
import 'horizontal_user_card.dart';
import 'simple_Info.dart';
import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';

class EmergencyPreparedness extends FStatefulWidget implements FPage {
  final List<DeviceInfoDTO> devices;
  final List<UserDTO> users;
  final GetEmergencySettingResult? setting;
  final void Function(String, String, PatientInfo?)? onPressed;
  EmergencyPreparedness({
    required this.devices,
    required this.users,
    this.onPressed,
    this.setting,
  });

  @override
  String get pageName => 'EmergencyPreparedness';

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

class _EmergencyPreparednessState extends FState<EmergencyPreparedness> {
  String _selectedUser = '';
  String _selectedDevice = '';
  List<SimpleInfoItem> _users = [];
  List<SimpleInfoItem> _devices = [];
  ConsultationServerConfig? emergencyConfig;
  bool _expandLess = true;
  ScrollController _scrollController = ScrollController();
  late final AppointmentConsultationController
      appointmentConsultationController;
  Map<String, String> patientDatas = {};
  ILanguageConfigManager languageManager = Get.find<ILanguageConfigManager>();
  GetEmergencySettingResult? get setting => widget.setting;

  @override
  FWidget build(BuildContext context) {
    if (kIsMobile) {
      return FScaffold(
        appBar: FAppBar.simple(
          title: i18nBook.realTimeConsultation.emergencyConfig.t,
          onBackClicked: router.back,
        ),
        body: FColumn(
          children: [
            FExpanded(
              child: FListView(
                shrinkWrap: true,
                controller: _scrollController,
                children: _buildItemsContentView(),
              ),
            ),
            _buildStartConsultationButton(),
          ],
        ),
      );
    }
    return FSimpleDialog(
      title: FText(
        i18nBook.realTimeConsultation.makeCall.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      bottomButton: _buildStartConsultationButton(),
      children: _buildItemsContentView(),
    );
  }

  @override
  void initState() {
    if (!kIsMobile) {
      appointmentConsultationController = Get.put(
        AppointmentConsultationController(
          realTimeConsultationController:
              Get.find<RealTimeConsultationController>(),
          isEmergency: true,
        ),
      );
    }
    for (var userInfo in widget.users) {
      var itemInfo = SimpleInfoItem(
        itemCode: userInfo.userCode ?? '',
        role: userInfo.rootOrganizationName,
        name: userInfo.displayName,
        des: userInfo.fieldList,
        image: userInfo.headImageUrl,
      );
      _users.add(itemInfo);
    }
    for (var device in widget.devices) {
      var itemInfo = SimpleInfoItem(
        itemCode: device.shortCode ?? '',
        role: device.shortCode,
        name: device.displayName,
        des: [device.description],
        image: device.headPicUrl,
      );
      _devices.add(itemInfo);
    }
    if (widget.users.isNotEmpty) {
      _selectedUser = widget.users.first.userCode ?? '';
    }
    if (widget.devices.isNotEmpty) {
      _selectedDevice = widget.devices.first.shortCode ?? '';
    }
    try {
      if (setting != null &&
          setting!.emergencyNeedFill &&
          setting!.emergencySettingJson.isNotNullOrWhiteSpace) {
        var jsonObject = jsonDecode(setting!.emergencySettingJson!);
        emergencyConfig = ConsultationServerConfig.fromJson(
            jsonObject['ConsultationInfo'], "1.0");
      }
    } catch (ex) {
      logger.e('EmergencyPreparedness JsonDecode ex:',
          "${setting?.emergencySettingJson} Error:${ex.toString()}");
    }
    super.initState();
  }

  FWidget _buildGridView(List<SimpleInfoItem> items, bool isSelectedUser) {
    return FGridView.builder(
      itemCount: items.length,
      controller: _scrollController,
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: kIsMobile ? 1 : 2,
        mainAxisSpacing: 5, // 垂直间距
        crossAxisSpacing: 10, // 水平间距
        childAspectRatio: 2.5, // 宽高比
      ),
      itemBuilder: (BuildContext context, int index) {
        var itemInfo = items[index];
        var itemCode = itemInfo.itemCode;
        return FHorizontalUserSimpleCard(
          itemInfo: itemInfo,
          margin: EdgeInsets.only(
              top: 5, left: kIsMobile ? 5 : 10, right: kIsMobile ? 5 : 10),
          height: 115,
          borderRadius: isSelectedUser ? 115 : 8,
          isUserHeadImage: isSelectedUser,
          isSelected: isSelectedUser
              ? _selectedUser == itemCode
              : _selectedDevice == itemCode,
          onTap: (selected) {
            if (selected ||
                (isSelectedUser
                    ? _selectedUser == itemCode
                    : _selectedDevice == itemCode)) {
              setState(() {
                isSelectedUser
                    ? _selectedUser = itemCode
                    : _selectedDevice = itemCode;
              });
            }
          },
        );
      },
    );
  }

  List<FWidget> _buildItemsContentView() {
    return [
      if (emergencyConfig != null) ...[
        _buildTitle(i18nBook.remedical.patientDetail.t),
        const FSizedBox(height: 10),
        _buildPatientInfo(),
      ],
      FContainer(
        color: Colors.grey[200],
        child: FRow(
          children: [
            _buildTitle(i18nBook.realTimeConsultation.selectExpert.t),
            FExpanded(child: FSizedBox()),
            FIconButton(
              icon: FIcon(_expandLess ? Icons.expand_less : Icons.expand_more),
              onPressed: () {
                setState(() {
                  _expandLess = !_expandLess;
                });
              },
              businessParent: widget,
              name: 'expand',
            ),
            FSizedBox(
              width: 10,
            ),
          ],
        ),
      ),
      if (_expandLess) ...[
        FContainer(
          width: 600,
          child: _buildGridView(
            _users,
            true,
          ),
        ),
      ],
      const FSizedBox(height: 10),
      FContainer(
        height: 48,
        alignment: Alignment.centerLeft,
        color: Colors.grey[200],
        child: _buildTitle(i18nBook.realTimeConsultation.selectDevice.t),
      ),
      const FSizedBox(height: 5),
      FContainer(
        width: 600,
        child: _buildGridView(
          _devices,
          false,
        ),
      ),
      const FSizedBox(height: 20),
    ];
  }

  FWidget _buildStartConsultationButton() {
    return FContainer(
      alignment: kIsMobile ? Alignment.bottomCenter : Alignment.center,
      margin: EdgeInsets.only(bottom: kIsMobile ? 0 : 15),
      child: FElevatedButton(
        child: FText(i18nBook.realTimeConsultation.startEmergency.t),
        onPressed: () {
          PatientInfo? patientInfo;
          if (emergencyConfig?.patientKeyList.isNotEmpty ?? false) {
            ///非空校验
            for (p.PatientModel pa in emergencyConfig?.patientKeyList ?? []) {
              if (!kIsMobile &&
                  pa.required &&
                  appointmentConsultationController
                      .patient[pa.key].isNullOrWhiteSpace) {
                PromptBox.toast(i18nBook.user.requiredFieldsCannotBeEmpty.t);
                return;
              } else if (kIsMobile && patientDatas[pa.key].isNullOrWhiteSpace) {
                PromptBox.toast(i18nBook.user.requiredFieldsCannotBeEmpty.t);
                return;
              }
            }

            if (kIsMobile) {
              patientInfo = PatientInfo(
                patientCode: patientDatas['PatientCode']!,
                name: patientDatas['Name'],
                identityCard: patientDatas['IdentityCard'],
                phone: patientDatas['Phone'],
              );
            } else {
              if (appointmentConsultationController
                  .state.currentPatient.patientCode.isNotEmpty) {
                patientInfo = PatientInfo(
                  patientCode: appointmentConsultationController
                      .state.currentPatient.patientCode,
                  name: appointmentConsultationController.patient['Name'],
                  phone: appointmentConsultationController.patient["Phone"],
                  identityCard:
                      appointmentConsultationController.patient['IdentityCard'],
                );
              }
            }
          }
          widget.onPressed?.call(_selectedUser, _selectedDevice, patientInfo);
        },
        businessParent: widget,
        name: 'Emergency start',
        style: ButtonStyle(
          padding: MaterialStateProperty.all(
            EdgeInsets.symmetric(vertical: kIsMobile ? 0 : 0),
          ),
          fixedSize: MaterialStateProperty.all(Size(
              kIsMobile ? MediaQuery.of(context).size.width : 120,
              kIsMobile ? 50 : 34)),
        ),
      ),
    );
  }

  FWidget _buildTitle(String text) {
    return FContainer(
      margin: EdgeInsets.symmetric(horizontal: 25),
      width: kIsMobile ? MediaQuery.of(context).size.width - 108 : 500,
      child: FText(
        text,
        softWrap: true,
        style: TextStyle(fontSize: 16, color: Colors.black87),
      ),
    );
  }

  FWidget _buildPatientInfo() {
    if (emergencyConfig == null) {
      return FSizedBox();
    }
    if (kIsMobile) {
      patientDatas = {};
      return MobileEmergencyConfig(
        emergencyConfig!.patientKeyList,
        patientDatas,
      );
    }
    return _deskTopEmergencyConfig();
  }

  FWidget _buildOnTapInput(String hintText, String value, [Function? onTap]) {
    return FContainer(
      child: FBorderInput(
        contentSize: 16,
        maxLength: 20,
        width: 300,
        borderColor: const Color.fromRGBO(230, 230, 230, 1),
        height: 38,
        hintSize: 16,
        readOnly: true,
        hintText: hintText,
        enableInteractiveSelection: false,
        enabled: true,
        controller: TextEditingController(text: value),
        onTap: onTap!(),
      ),
    );
  }

  FWidget _deskTopEmergencyConfig() {
    return FConfigureLayoutStyle(
      width: 600,
      child: FColumn(
        children: [
          ...emergencyConfig!.patientKeyList.map((e) {
            switch (e.showType) {
              case 'input':
                return FConfigureLayout(
                  title: languageManager.getConsultationLanguageValue(
                    e.key,
                  ),
                  widget: FConfigureInput(
                    hintText: i18nBook.common.input.translate(
                      [
                        languageManager.getConsultationLanguageValue(
                          e.key,
                        ),
                      ],
                    ),
                    inputFormatters: _getInputFormatters(e.desc),
                    textController: TextEditingController(
                      text: appointmentConsultationController.patient
                              .containsKey(e.key)
                          ? appointmentConsultationController.patient[e.key]
                          : '',
                    ),
                    onChanged: (value) {
                      appointmentConsultationController.patient[e.key] =
                          value.toString().trim();
                    },
                    enabled: true,
                  ),
                  isRequired: e.required,
                );
              case 'inputButton':
                return FConfigureLayout(
                  title: languageManager.getConsultationLanguageValue(
                    e.key,
                  ),
                  isRequired: e.required,
                  widget: FExpanded(
                    child: _buildOnTapInput(
                      i18nBook.realTimeConsultation
                          .pleaseSelectPatientForConsultation.t,
                      appointmentConsultationController.patient
                              .containsKey(e.key)
                          ? appointmentConsultationController.patient[e.key] ??
                              ''
                          : '',
                      () => () async {
                        await Get.dialog(
                          FObx(
                            () => FSelectPatient(
                              selectList: appointmentConsultationController
                                  .state.patientList,
                            ),
                          ),
                        );
                        setState(() {});
                      },
                    ),
                  ),
                );
              default:
                return FSizedBox();
            }
          }).toList(),
        ],
      ),
    );
  }

  List<TextInputFormatter>? _getInputFormatters(String desc) {
    if (desc == "PatientPhone") {
      return [PageInputFormatters.number];
    } else if (desc == "PatientIdentityCard") {
      return [PageInputFormatters.letterAndNumber];
    }
    return null;
  }
}
