import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/consultation_server_config.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/managers/interfaces/language.dart';
import 'package:flyinsono/managers/interfaces/remedical.dart';
import 'package:flyinsono/pages/consultation/consultation_detail/widgets/select_patient.dart';
import 'package:flyinsono/pages/element_static.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:flyinsono/views/desktop/appointment_consultation/widgets/select_patient_dialog.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;
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:fis_common/helpers/encrypt.dart';

///手机端急诊配置中的病人详情部分
class MobileEmergencyConfig extends FStatefulWidget {
  MobileEmergencyConfig(this.patientKeyList, this.patientinfo);

  final List<PatientModel> patientKeyList;

  final Map<String, String> patientinfo;

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

class _MobileEmergencyConfigState extends FState<MobileEmergencyConfig> {
  Map<String, String> patientinfo = {};
  final languageManager = Get.find<ILanguageConfigManager>();
  final remedicalManager = Get.find<IRemedicalManager>();

  @override
  void didUpdateWidget(MobileEmergencyConfig oldWidget) {
    ///页面resize时保持widget的值和当前页面的值一致
    patientinfo.keys.forEach((key) {
      widget.patientinfo[key] = patientinfo[key] ?? '';
    });
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    patientinfo = widget.patientinfo;
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FConfigureLayoutStyle(
      width: MediaQuery.of(context).size.width,
      child: FContainer(
        margin: EdgeInsets.only(right: 20),
        child: FColumn(
          children: [
            ...widget.patientKeyList.map((e) {
              switch (e.showType) {
                case 'input':
                  return _buildInputLine(e);
                case 'inputButton':
                  return _buildInputButtonLine(e);
                default:
                  return FSizedBox();
              }
            }).toList(),
          ],
        ),
      ),
    );
  }

  FWidget _buildInputLine(PatientModel e) {
    return FConfigureLayout(
      title: languageManager.getConsultationLanguageValue(
        e.key,
      ),
      titleWidth: i18nBook.isCurrentChinese ? 100 : 120,
      widget: FConfigureInput(
        hintText: i18nBook.common.input.translate(
          [
            languageManager.getConsultationLanguageValue(
              e.key,
            ),
          ],
        ),
        inputFormatters: _getInputFormatters(e.desc),
        textController: TextEditingController(
          text: patientinfo.containsKey(e.key) ? patientinfo[e.key] : '',
        ),
        onChanged: (value) {
          var valueStr = value.toString().trim();
          patientinfo[e.key] = valueStr;
          widget.patientinfo[e.key] = valueStr;
        },
        enabled: true,
      ),
      isRequired: e.required,
    );
  }

  FWidget _buildInputButtonLine(PatientModel e) {
    return FConfigureLayout(
      title: languageManager.getConsultationLanguageValue(
        e.key,
      ),
      titleWidth: i18nBook.isCurrentChinese ? 100 : 120,
      isRequired: e.required,
      widget: FExpanded(
        child: _buildOnTapInput(
          i18nBook.realTimeConsultation.pleaseSelectPatientForConsultation.t,
          patientinfo.containsKey(e.key) ? patientinfo[e.key] ?? '' : '',
          () => () async {
            await openSelectPatientPage();
            setState(() {});
          },
        ),
      ),
    );
  }

  Future<bool> openSelectPatientPage() async {
    var patients = await remedicalManager.findSimpleInfoPatients(
      isCounsultationPatient: true,
    );
    bool isAddPatient = false;
    await Get.to<bool>(SelectPatientPage(
      (p) async {
        var patientCode = p.itemCode;
        var patientInfoDto =
            await remedicalManager.findPatientByCode(patientCode);
        var patient = remedicalManager.dtoConvertToPatientInfo(patientInfoDto);
        patientinfo['Name'] = patient.name ?? '';
        patientinfo['Phone'] = patient.phone ?? '';
        patientinfo['IdentityCard'] = patient.identityCard ?? '';
        patientinfo['PatientCode'] = patient.patientCode;
        patientinfo.keys.forEach((key) {
          widget.patientinfo[key] = patientinfo[key] ?? '';
        });
        router.back();
      },
      patients,
      onAdd: (name) async {
        if (name.isNullOrWhiteSpace) {
          PromptBox.toast(i18nBook.errorCodes.errorCode4052.t);
          return false;
        }
        var result =
            await remedicalManager.createPatientByUnregisteredAsync(name);
        isAddPatient = result;
        return result;
      },
      isCounsultationPatient: true,
    ));
    return isAddPatient;
  }

  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!(),
      ),
    );
  }

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