import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/services/appletAPI.m.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

import 'index.dart';

class WxReportsListController extends GetxController {
  WxReportsListController();

  /// 滑动控制器
  final ScrollController gridViewScrollController = ScrollController();

  // /// 当前页码
  // int _currentPage = 1;

  // /// 每页条数
  // int _pageSize = 10;

  /// 总条数
  int _totalCount = 0;

  int get totalCount => _totalCount;

  final state = WxReportsListState();

  // 数据获取方式
  WxReportListPageArguments? _dataFetchArgs;

  /// 监听滑动事件
  // void addScrollListener() {
  //   gridViewScrollController.addListener(() async {
  //     // 如果滑动到底部
  //     try {
  //       if (gridViewScrollController.position.atEdge) {
  //         if (gridViewScrollController.position.pixels != 0) {
  //           if (state.reportIdList.length < _totalCount) {
  //             CommonUtil.debounce(() {
  //               _currentPage = _currentPage + 1;
  //               _fetchData();
  //             });
  //           }
  //         }
  //       }
  //     } catch (e) {
  //       logger.e("gridViewScrollController exception:", e);
  //     }
  //   });
  // }

  void handleShowDetail(int index) {
    print("handleShowDetail $index");
    Get.toNamed(MobileRouteNames.Wechat.MiniProgramReportDetail,
        arguments: state.reportInfoList[index]);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() async {
    _initData();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 下拉刷新
  Future<void> refreshList() async {
    if (_dataFetchArgs == null) return;
    try {
      if (_dataFetchArgs!.dataFetchType ==
          WxReportListDataFetchType.ByRemedicalRecordId) {
        final String remedicalRecordId = _dataFetchArgs!.remedicalRecordId;
        state.reportInfoList =
            await _getReportIdListByRemedicalRecordId(remedicalRecordId);
      } else {
        final String consultationId = _dataFetchArgs!.consultationId;
        state.reportInfoList =
            await _getReportIdListByConsultationId(consultationId);
      }
      _totalCount = state.reportInfoList.length;
      state.noData = _totalCount == 0;
    } catch (e) {
      logger.e("refreshList exception:", e);
    }
  }

  /// 数据初始化
  void _initData() async {
    final arguments = Get.arguments;
    if (!(arguments is WxReportListPageArguments)) return;
    _dataFetchArgs = arguments;
    if (arguments.dataFetchType ==
        WxReportListDataFetchType.ByRemedicalRecordId) {
      final String remedicalRecordId = arguments.remedicalRecordId;
      state.reportInfoList =
          await _getReportIdListByRemedicalRecordId(remedicalRecordId);
    } else {
      final String consultationId = arguments.consultationId;
      state.reportInfoList =
          await _getReportIdListByConsultationId(consultationId);
    }
    _totalCount = state.reportInfoList.length;
    state.noData = _totalCount == 0;
    print("initData _totalCount $_totalCount");
  }

  // 通过 RemedicalRecordId 查询
  Future<List<ReportInfo>> _getReportIdListByRemedicalRecordId(
      String remedicalRecordId) async {
    String openid = Store.user.token;
    List<ReportInfo> result = await rpc.appletAPI
        .getRemedicalReportListAsync(GetRemedicalReportListRequest(
      openId: openid,
      remedicalRecordId: remedicalRecordId,
    ));
    return result;
  }

  // 通过 ConsultationId 查询
  Future<List<ReportInfo>> _getReportIdListByConsultationId(
      String consultationId) async {
    String openid = Store.user.token;
    List<ReportInfo> result = await rpc.appletAPI
        .getConsultationReportListAsync(GetConsultationReportListRequest(
      openId: openid,
      consultationId: consultationId,
    ));
    return result;
  }
}

class WxReportListPageArguments {
  // 数据载入方式
  final WxReportListDataFetchType dataFetchType;
  // 会诊ID
  final String remedicalRecordId;
  // 诊断ID
  final String consultationId;

  WxReportListPageArguments({
    required this.dataFetchType,
    this.remedicalRecordId = "",
    this.consultationId = "",
  });
}

// 数据载入方式
enum WxReportListDataFetchType {
  // 通过 RemedicalRecordId 查询
  ByRemedicalRecordId,
  // 通过 ConsultationId 查询
  ByConsultationId,
}
