import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/js_platform/listener.dart';
import 'package:flyinsono/managers/interfaces/entities/patient_Info.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/controller.dart';
import 'package:flyinsono/pages/remedical/consultation_record_view/state.dart';
import 'package:flyinsono/rpc.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:get/get.dart';
import 'package:fis_ui/index.dart';

import 'package:fis_jsonrpc/services/index.dart';

class CheckController {
  final ConsultationRecordViewController controller;

  ConsultationRecordViewState get state => controller.state;

  CheckController(this.controller);

  List<PatientInfo> selectPatientInfosList = []; // 下拉选择的病人列表
  Map<String, dynamic> patientInfo = {}; // 新增的病人信息
  String patientName = ''; // 病人姓名

  /// 获取病人数据
  Map<String, String> getPatientValue(
    List<DataItemDTO> patientData,
  ) {
    return {
      'Name': handlePatientValue(patientData, 'Name'),
      'Age': handlePatientValue(patientData, 'Age'),
      'Sex': handlePatientValue(patientData, 'Sex'),
      'Phone': handlePatientValue(patientData, 'Phone'),
      'Birthday': handlePatientValue(patientData, 'Birthday'),
      'AgeYear': handlePatientValue(patientData, 'AgeYear'),
      'AgeMonth': handlePatientValue(patientData, 'AgeMonth'),
      'AgeWeek': handlePatientValue(patientData, 'AgeWeek'),
      'AgeDay': handlePatientValue(patientData, 'AgeDay'),
      'AgeUnits': handlePatientValue(patientData, 'AgeUnits'),
      'Anamnesis': handlePatientValue(patientData, 'Anamnesis'),
      'HeadImgUrl': handlePatientValue(patientData, 'HeadImgUrl'),
      'AnimalInfoName': handlePatientValue(patientData, 'AnimalInfoName'),
      'ExaminingPhysician':
          handlePatientValue(patientData, 'ExaminingPhysician'),
      'MedicalHistory': handlePatientValue(patientData, 'MedicalHistory'),
    };
  }

  /// 处理病人参数
  String handlePatientValue(List<DataItemDTO> patientData, String value) {
    return patientData
            .firstWhereOrNull(
              (element) => element.key == value,
            )
            ?.value ??
        '';
  }

  /// 处理病人数据
  void handleConsultationPatient(
    List<ClientPatientInfoBaseDTO> clientPatients,
  ) {
    final List<PatientInfo> _selectPatientInfosList = [];
    PatientInfo patientInfo;

    for (int i = 0; i < clientPatients.length; i++) {
      final List<DataItemDTO> patientData = clientPatients[i].patientData ?? [];
      Map<String, String> patientValues = getPatientValue(patientData);
      final String name = _getPatientName(patientValues);
      final String age = patientValues['Age'] ?? '';
      final String sex = patientValues['Sex'] ?? '';
      final String phone = patientValues['Phone'] ?? '';
      final String birthday = patientValues['Birthday'] ?? '';
      final String ageYear = patientValues['AgeYear'] ?? '';
      final String ageMonth = patientValues['AgeMonth'] ?? '';
      final String ageWeek = patientValues['AgeWeek'] ?? '';
      final String ageDay = patientValues['AgeDay'] ?? '';
      final String ageUnits = patientValues['AgeUnits'] ?? '';
      final String anamnesis = patientValues['Anamnesis'] ?? '';
      final String headImgUrl = patientValues['HeadImgUrl'] ?? '';
      final String examiningPhysician =
          patientValues['ExaminingPhysician'] ?? '';
      final String medicalHistory = patientValues['MedicalHistory'] ?? '';
      patientInfo = PatientInfo(
        isValid: clientPatients[i].isValid,
        createTime: clientPatients[i].createTime ?? DateTime.now(),
        patientCode: clientPatients[i].patientCode ?? '',
        name: name,
        age: age,
        sex: sex,
        phone: phone,
        birthday: birthday,
        ageYear: ageYear,
        ageMonth: ageMonth,
        ageWeek: ageWeek,
        ageDay: ageDay,
        ageUnits: ageUnits,
        anamnesis: anamnesis,
        headImgUrl: headImgUrl,
        examiningPhysician: examiningPhysician,
        medicalHistory: medicalHistory,
      );
      _selectPatientInfosList.add(patientInfo);
    }
    selectPatientInfosList = _selectPatientInfosList;
  }

  /// 搜索病人
  void searchPatient() async {
    await findConsultationPatientAsync();
    if (selectPatientInfosList.isEmpty) {
      confirmAlertAddNewPatient();
    }
  }

  /// 二次弹框 是否是新创建病人
  void confirmAlertAddNewPatient() {
    var container = JsListener();
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.remedical.hint4patientNotFound.translate(
        [patientName],
      ),
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () async {
        await createPatient();
      },
      businessParent: container,
    );
  }

  void updatePatientListUI() {
    controller.update(["patient_list"]);
  }

  /// 创建病人
  Future<void> createPatientByUnregisteredAsync(
    String patientName,
  ) async {
    try {
      final result = await rpc.patient.createPatientByUnregisteredAsync(
        CreatePatientByUnregisteredRequest(
          token: Store.user.token,
          patientName: patientName,
        ),
      );
      await findConsultationPatientAsync();
      if (!result) {
        PromptBox.toast(i18nBook.remedical.creatFailed.t);
      }
    } catch (e) {
      printError(info: "createPatientByUnregisteredAsync exception:$e");
      logger.e("createPatientByUnregisteredAsync exception:", e);
    }
  }

  /// 获取病人列表数据
  Future<void> findConsultationPatientAsync() async {
    try {
      final result = await rpc.liveConsultation.findConsultationPatientAsync(
        FindConsultationPatientPageRequest(
          token: Store.user.token,
          keyword: patientName,
          pageIndex: 1,
          pageSize: 100,
        ),
      );
      handleConsultationPatient(result.pageData ?? []);
      updatePatientListUI();
    } catch (e) {
      logger.e('msg', e);
    }
  }

  /// 检查 新增病人信息
  Future<void> createPatient() async {
    if (patientName.isEmpty) {
      PromptBox.toast(
          i18nBook.realTimeConsultation.pleaseEnterCreatedPatientName.t);
      return;
    }
    final name = FEncryptHelper.encodeBase64(patientName);
    await createPatientByUnregisteredAsync(
      name,
    );
  }

  String _getPatientName(Map<String, String> patientValues) {
    var name = patientValues['Name'];
    if (name == null || name.isEmpty) {
      name = patientValues['AnimalInfoName'];
    }
    return name!;
  }
}
