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/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 'state.dart';

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

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

  final crowdLabelsController = CrowdLabelsController();

  /// 前进到检测页面
  Future<void> gotoDetail(String code) async {
    Get.back();

    if (!Get.isRegistered<MedicalController>()) {
      Get.lazyPut(() => MedicalController());
    }
    final medicalController = Get.find<MedicalController>();

    PatientDTO? patientInfoDto = await _patientManager.getDetail(code);
    Store.user.currentSelectPatientInfo = patientInfoDto;

    await _patientDetailController.loadData();
    await medicalController.initData();
    _homeController.updateMenus();
    _homeController.switchNavByName("/medical");
    //这里应该刷新病人诊断数据缓存
    // _medicalController.changePatient.emit(this, code);
  }

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

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

  @override
  void onReady() {
    reloadList();
    super.onReady();
  }

  /// 重新加载列表
  Future<void> reloadList({bool isFilter = false}) async {
    state.pageIndex = 0;
    state.dataList = [];
    await loadNextPageList(isFilter: isFilter);
  }

  /// 加载下一页列表
  Future<void> loadNextPageList({bool isFilter = false}) async {
    final request = PatientPageRequest(
      pageIndex: state.pageIndex + 1,
      pageSize: state.pageSize,
      keyword: !isFilter ? state.searchString : "",
      startTime: state.startTime.value,
      endTime: state.endTime.value,
      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!);
      }
    }
  }
}
