import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/network_connectivity.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/global.dart';
import 'package:vitalapp/managers/interfaces/diagnosis.dart';
import 'package:vitalapp/managers/interfaces/models/diagnosis_aggregation_record_model.dart';
import 'package:vitalapp/managers/interfaces/patient.dart';
import 'package:vitalapp/pages/controllers/home_nav_mixin.dart';
import 'package:vitalapp/pages/facial_recognition/index.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';
import 'state.dart';

class PatientDetailController extends FControllerBase with HomeNavMixin {
  final state = PatientDetailState();
  final _patientManager = Get.find<IPatientManager>();

  @override
  void onInit() {
    WidgetsBinding.instance.addPostFrameCallback(
      (timeStamp) async {
        await loadData();
        netChecker.onlineChangedEvent.addListener(_onlineChanged);
      },
    );

    super.onInit();
  }

  void _onlineChanged(_, e) {
    state.isOnline = e;
  }

  /// 打开信息页
  void gotoInfo() {
    Get.toNamed(
      "/patient/info",
      parameters: {"code": state.code},
    );
  }

  /// 前往随访页
  void gotoFollowUp() {
    Get.toNamed(
      "/check/follow_up",
      parameters: {"patientCode": state.code, "patientName": state.name},
    );
  }

  /// 前往随访记录页
  void gotoFollowUpRecord() {
    Get.toNamed(
      "/check/follow_up_record",
      parameters: {"patientCode": state.code, "patientName": state.name},
    );
  }

  /// 前往健康体检页
  void gotoHealthCheck() {
    Get.toNamed(
      "/check/form",
      parameters: {"patientCode": state.code},
    );
  }

  /// 前往签约页
  void gotoContract() {
    Get.toNamed(
      "/contract/package_list",
      parameters: {"patientCode": state.code},
    );
  }

  /// 前往转诊页
  void gotoReferral() {
    //
  }

  /// 前往健康检测页
  void gotoExam() {
    //
    Get.toNamed(
      "/medical",
      parameters: {"patientCode": state.code},
    );
  }

  /// 前往诊疗记录页
  void gotoExamRecord() {
    //
    Get.toNamed(
      "/medical/records",
      parameters: {"patientCode": state.code},
    );
  }

  ///前往体检记录
  void gotoHealthCheckRecord() {
    Get.toNamed(
      "/check/healthCheckRecord",
      parameters: {"patientCode": state.code},
    );
  }

  void gotoContractRecords() {
    Get.toNamed(
      "/contract/contract_records",
      parameters: {"patientCode": state.code},
    );
  }

  /// 人脸录入
  Future<void> queryIsNeedFaceInput() async {
    var dto =
        await getPatientPhoto(Store.user.currentSelectPatientInfo!.cardNo!);
    await onFaceEntryClicked(dto);
    Get.back();
  }

  /// 点击录入人脸
  Future<void> onFaceEntryClicked(PatientDTO? dto) async {
    bool? result = await Get.to<bool>(
      () => FacialRecognitionPage(
        mode: FacialRecognitionMode.faceInput,
        patientInfo: dto,
      ),
    );
    if (result != null && result) {
      await loadData();
      PromptBox.toast('人脸数据存入成功');
    }
  }

  Future<PatientDTO?> getPatientPhoto(String patientCode) async {
    try {
      final dto = await _patientManager.getDetail(patientCode);
      return dto;
    } catch (e) {
      return null;
    }
  }

  Future<void> loadData({String code = ''}) async {
    PatientDTO? dto;
    if (code.isNotEmpty) {
      dto = await getPatientPhoto(code);
    } else if (Store.user.currentSelectPatientInfo != null &&
        Store.user.currentSelectPatientInfo!.code != null) {
      dto = await getPatientPhoto(Store.user.currentSelectPatientInfo!.code!);
      dto ??= Store.user.currentSelectPatientInfo;
    }
    if (dto != null) {
      state.code = dto.code ?? '';
      dto.birthday = dto.birthday!.toLocal();
      state.updateDto(dto);
    }
  }

  Future<bool> setCrowdLabelsAsync(
      List<String> carowLabels, List<String> crowdNames) async {
    final result =
        await _patientManager.setCrowdLabelsAsync(state.code, carowLabels);
    if (result) {
      state.updateCrowd(carowLabels, crowdNames);
    }
    return result;
  }

  /// 读取到最近检测记录的数据
  Future<void> onReadLastRecordInfo() async {
    try {
      if (Store.user.currentSelectPatientInfo?.code != null) {
        var diagnosisManager = Get.find<IDiagnosisManager>();
        List<DiagnosisAggregationRecordModel> getRecords = [];
        logger.i('onReadLastRecordInfo: 开始获取 最近检测记录.');

        /// 这是在线的
        if (kIsOnline) {
          var getLastRecords =
              await diagnosisManager.getDiagnosisAggregationPageAsync(
                  Store.user.currentSelectPatientInfo!.code!, 1, 10);
          if (getLastRecords != null) {
            getRecords.addAll(getLastRecords.pageData ?? []);
            logger.i(
                'PatientDetailController onReadLastRecordInfo getLastRecords.length:${getLastRecords.dataCount}.');
          } else {
            logger.i(
                'PatientDetailController onReadLastRecordInfo no online data available.');
          }
        }

        /// 这是离线的
        var listRecords = await diagnosisManager
            .getListByPatientCode(Store.user.currentSelectPatientInfo!.code!);
        if (listRecords != null) {
          getRecords.addAll(listRecords);
          logger.i(
              'PatientDetailController onReadLastRecordInfo listRecords.length:${listRecords.length}.');
        } else {
          logger.i(
              'PatientDetailController onReadLastRecordInfo no local data available.');
        }
        if (getRecords.isNotEmpty) {
          var lastRecordInfo = getRecords.reduce((curr, next) =>
              (curr.diagnosisTime!).isAfter(next.diagnosisTime!) ? curr : next);
          state.isExistLocalData = lastRecordInfo.isExistLocalData ?? false;
          state.currentDiagnosis = await diagnosisManager
              .getTableData(lastRecordInfo, isLastRecord: true);
          logger.i('onReadLastRecordInfo: ${lastRecordInfo.toJson()}');
        } else {
          state.currentDiagnosis = [];
          logger.i('onReadLastRecordInfo: empty');
        }
      }
    } catch (e) {
      logger.e('PatientDetailController onReadLastRecordInfo.', e);
    }
  }

  @override
  void onClose() {
    netChecker.onlineChangedEvent.removeListener(_onlineChanged);
  }
}
