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/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 crowdLabelsController = CrowdLabelsController();

  /// TODO 需要优化一下
  /// 前进到详情页
  Future<void> gotoDetail(String code) async {
    _homeController.updateMenus();
    _homeController.currentIndex = -1;
    _homeController.switchNavByName('/dashboard');
    Get.back();
    PatientDTO? patientInfoDto = await _patientManager.getDetail(code);
    // String patientInfo = jsonEncode(patientInfoDto);
    Store.user.currentSelectPatientInfo = patientInfoDto;

    _homeController.switchNavByName('/patient/detail');
    Get.find<PatientDetailController>().loadData();
    // Get.offAllNamed('/patient/detail', id: 1001);
    _homeController.currentIndex = 1;
  }

  /// 新建档案
  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: state.searchString,
      startTime: isFilter ? state.startTime.value : null,
      endTime: isFilter ? state.endTime.value : null,
    );
    if (state.searchString.isNotEmpty) {
      // TODO:
      // request.filter = {
      //   "xxx": state.searchString,
      // };
      // request.isFuzzy = true;
    }
    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!);
      }
    }
  }
}
