import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.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/index.dart';
import 'package:get/get.dart';
import 'index.dart';

class WxConsultationController extends GetxController {
  final state = WxConsultationState();

  /// 搜索框控制器
  final TextEditingController searchBarTextController = TextEditingController();

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

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

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

  /// 总条数
  int _totalCount = 0;

  WxConsultationController();
  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.consultationList.length < _totalCount) {
              CommonUtil.debounce(() {
                _currentPage = _currentPage + 1;
                _fetchData();
              });
            }
          }
        }
      } catch (e) {
        logger.e("listViewScrollController exception:", e);
      }
    });
  }

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

  /// 新建
  void handleCreateConsultation() async {
    var result = await Get.toNamed(
        MobileRouteNames.Wechat.MiniProgramConsultationCreate);
    print("handleCreateConsultation result $result");
    if (result != null && result is bool && result) {
      Get.snackbar(
        "成功",
        "会诊创建成功",
      );
      handleSearch();
    }
  }

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

  /// 会诊详情
  void handleShowDetail(int index) {
    print("handleConsultationDetail $index");
    Get.toNamed(
      MobileRouteNames.Wechat.MiniProgramConsultationDetail,
      arguments: state.consultationList[index],
    );
  }

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

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

  List<WxImagesModel> _getImagesListFromConsultationInfo(
      ConsultationInfo info) {
    List<WxImagesModel> list = [];
    // 遍历 info 的 imageTokens 和 videoInfos 取出视频和图像。，存入 list
    if (info.imageTokens != null && info.imageTokens!.isNotEmpty) {
      info.imageTokens!.forEach((element) {
        list.add(WxImagesModel(
            previewImageUrl: element.previewToken ?? '',
            vidFileUrl: element.imageToken ?? '',
            fileType: WxImagesType.SingleFramePng));
      });
    }
    // TODO 暂时不解析 videoInfos ，数据错误
    // if (info.videoInfos != null && info.videoInfos!.isNotEmpty) {
    //   info.videoInfos!.forEach((element) {
    //     list.add(WxImagesModel(
    //         previewImageUrl: element.previewToken ?? '',
    //         vidFileUrl: element.videoToken ?? '',
    //         fileType: WxImagesType.MultiFrameVid));
    //   });
    // }
    return list;
  }

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

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

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

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

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

  /// 查询预约会诊列表
  Future<List<ConsultationInfo>> _getConsultationList() async {
    String openId = Store.user.openid;
    int currentPage = _currentPage;
    int pageSize = _pageSize;
    String keyword = _searchKeyword;
    print(
        "查询预约会诊列表 openid:$openId currentPage:$currentPage pageSize:$pageSize keyword:$keyword");
    PageResult<ConsultationInfo> result =
        await rpc.appletAPI.getConsultationListAsync(GetConsultationListRequest(
      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 [];
    }
  }
}
