import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_images_list/controller.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_reports_list/controller.dart';
import 'package:get/get.dart';

import 'index.dart';

class WxDiagnosisController extends GetxController {
  /// 搜索框控制器
  final TextEditingController searchBarTextController = TextEditingController();

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

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

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

  /// 总条数
  int _totalCount = 0;

  final state = WxDiagnosisState();

  WxDiagnosisController();

  int get totalCount => _totalCount;

  /// 搜索关键词
  String get _searchKeyword => searchBarTextController.text;

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

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

  /// 搜索
  void handleSearch() async {
    try {
      _currentPage = 1;
      state.diagnosisList.clear();
      state.diagnosisList = await _getDiagnosisList();
    } catch (e) {
      logger.e("handleSearch exception:", e);
    }
  }

  /// 会诊详情
  void handleShowDetail(int index) {
    print("handleConsultationDetail $index");
    // Get.toNamed(MobileRouteNames.Wechat.MiniProgramDiagnosisDetail);
  }

  /// 打开报告列表
  void handleOpenReportList(int index) {
    print("handleOpenReportList $index");
    Get.toNamed(
      MobileRouteNames.Wechat.MiniProgramReports,
      arguments: WxReportListPageArguments(
        dataFetchType: WxReportListDataFetchType.ByRemedicalRecordId,
        remedicalRecordId: state.diagnosisList[index].remedicalRecordId ?? '',
      ),
    );
  }

  /// 打开图像列表
  void handleOpenImageList(int index) {
    print("handleOpenImageList $index");
    Get.toNamed(MobileRouteNames.Wechat.MiniProgramImages,
        arguments: WxImagesListPageArguments(
          dataFetchType: WxImagesListDataFetchType.FetchById,
          remedicalRecordId: state.diagnosisList[index].remedicalRecordId,
        ));
  }

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

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() async {
    super.onInit();
    state.diagnosisList = await _getDiagnosisList();
    state.firstLoad = false;
  }

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

  /// 下拉刷新
  Future<void> refreshList() async {
    try {
      _currentPage = 1;
      state.diagnosisList.clear();
      state.diagnosisList = await _getDiagnosisList();
      // FIXME remove delay
      await Future.delayed(const Duration(seconds: 1));
    } catch (e) {
      logger.e("refreshList exception:", e);
    }
  }

  /// 获取诊断列表
  Future<void> _fetchData() async {
    try {
      state.diagnosisList.addAll(await _getDiagnosisList());
    } catch (e) {
      logger.e("getPatients exception:", e);
    }
  }

  /// 查询远程诊断列表
  Future<List<RemedicalRecordInfo>> _getDiagnosisList() async {
    String openId = Store.user.openid;
    int currentPage = _currentPage;
    int pageSize = _pageSize;
    String keyword = _searchKeyword;
    print(
        "查询远程诊断列表 openid:$openId currentPage:$currentPage pageSize:$pageSize keyword:$keyword total:$_totalCount");
    PageResult<RemedicalRecordInfo> result = await rpc.appletAPI
        .getRemedicalRecordListAsync(GetRemedicalRecordListRequest(
      openId: openId,
      pageIndex: currentPage,
      pageSize: pageSize,
      keyWord: keyword,
    ));
    print("返回数据量: ${result.pageData!.length}");
    if (result.pageData!.length < _pageSize) {
      _totalCount = _pageSize * (_currentPage - 1) + result.pageData!.length;
    } else {
      _totalCount =
          _pageSize * (_currentPage - 1) + result.pageData!.length + 1;
    }
    if (result.pageData != null) {
      result.pageData!.forEach((element) {
        print("查询远程诊断列表返回值: ${element.toJson()}");
      });
      return result.pageData!;
    } else {
      return [];
    }
  }
}
