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/global.dart';
import 'package:vitalapp/managers/interfaces/patient.dart';
import 'package:vitalapp/pages/controllers/crowd_labels.dart';
import 'package:vitalapp/pages/home/controller.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/patient/detail/controller.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';
import 'state.dart';

class PatientListController extends FControllerBase {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  final state = PatientListState();
  final _homeController = Get.find<HomeController>();
  final _patientDetailController = Get.find<PatientDetailController>();

  // final createPatientController = Get.find<CreatePatientController>();
  final _patientManager = Get.find<IPatientManager>();

  final crowdLabelsController = CrowdLabelsController();
  void patientListGotoDetail(PatientDTO dto) async {
    Store.user.currentSelectPatientInfo = dto;
    logger.i('list切换居民 当前居民是：${dto.patientName} 居民code：${dto.code}');
    gotoDetail(dto.code!);
  }

  /// 前进到用户详情页面
  Future<void> gotoDetail(
    String code, [
    PatientDTO? patientInfoDto,
    PatientBaseDTO? patientInfo,
  ]) async {
    if (!Get.isRegistered<MedicalController>()) {
      Get.lazyPut(() => MedicalController());
    }
    final medicalController = Get.find<MedicalController>();
    await _patientDetailController.loadData(code: code);
    _homeController.updateMenus();
    _homeController.switchNavByName("/patient/detail");
    await medicalController.initData();
    //这里应该刷新病人诊断数据缓存
    // _medicalController.changePatient.emit(this, code);
  }

  Future<void> gotoCreate(
    String code, [
    PatientDTO? patientInfoDto,
    PatientBaseDTO? patientInfo,
  ]) async {
    _homeController.initMenus();
    if (patientInfo != null) {
      _homeController.switchNavByName(
        "/patient/create",
        patientInfo.toJson(),
      );
    }
  }

  /// 新建档案
  void onCreateClicked() {
    // Get.toNamed(
    //   "/patient/create",
    //   id: 1001,
    //   parameters: {"from": "list"},
    // );
    _homeController.switchNavByName("/patient/create");
  }

  /// 筛选
  void onFilterClicked() {
    Get.snackbar("提示", "尚未开发此功能");
  }

  @override
  void onReady() {
    reloadList();
    netChecker.onlineChangedEvent.addListener(_onlineChanged);
    super.onReady();
  }

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

  /// 重新加载列表
  Future<void> reloadList({bool isFilter = false}) async {
    busy = true;
    state.pageIndex = 0;
    state.dataList = [];
    if (kIsOnline) {
      final request = PatientPageRequest(
        keyword: state.searchString,
        startTime: state.startTime.value,
        endTime: state.endTime.value?.add(const Duration(days: 1)),
        crowdLabels: crowdLabelsController.state.selectedCodes,
      );
      var offlineList = await _patientManager.getPagedOfflineList(request);
      if (offlineList != null) state.appendDataList(offlineList);
    }

    await loadNextPageList(isFilter: isFilter);
  }

  /// 加载下一页列表
  Future<void> loadNextPageList({bool isFilter = false}) async {
    busy = true;
    final request = PatientPageRequest(
      pageIndex: state.pageIndex + 1,
      pageSize: state.pageSize,
      keyword: state.searchString,
      startTime: state.startTime.value,
      endTime: state.endTime.value?.add(const Duration(days: 1)),
      crowdLabels: crowdLabelsController.state.selectedCodes,
    );

    final pagedList = await _patientManager.getPagedList(request);
    if (pagedList != null) {
      state.totalCount = pagedList.dataCount;
      if (pagedList.pageData != null) {
        state.pageIndex = state.pageIndex + 1;
        state.appendDataList(pagedList.pageData!);
      }
    }
    busy = false;
  }

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