import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:vnoteapp/architecture/defines.dart';
import 'package:vnoteapp/managers/interfaces/patient.dart';
import 'package:vnoteapp/pages/home/controller.dart';

import 'state.dart';

class PatientListController extends FControllerBase {
  final _patientManager = Get.find<IPatientManager>();

  final state = PatientListState();

  /// 前进到详情页
  Future<void> gotoDetail(String code) async {
    PatientDTO? patientInfoDto = await _patientManager.getDetail(code);
    String patientInfo = jsonEncode(patientInfoDto);
    Get.toNamed(
      "/patient/detail",
      parameters: {
        "code": code,
        "patientInfo": patientInfo,
      },
    );
  }

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

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

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

  /// 重新加载列表
  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!);
      }
    }
  }
}
