import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/services/appletAPI.m.dart';
import 'package:fis_jsonrpc/services/liveConsultation.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/architecture/utils/common_util.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_image_preview/controller.dart';
import 'package:get/get.dart';

import 'index.dart';

class WxImagesListController extends GetxController {
  WxImagesListController();

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

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

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

  /// 总条数
  int _totalCount = 0;

  /// 全量载入模式
  bool _fullLoadMode = false;

  int get totalCount => _totalCount;

  String _remedicalRecordId = "";

  final state = WxImagesListState();

  /// 监听滑动事件
  void addScrollListener() {
    gridViewScrollController.addListener(() async {
      // 如果滑动到底部
      try {
        if (gridViewScrollController.position.atEdge) {
          if (gridViewScrollController.position.pixels != 0) {
            if (state.imageList.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.MiniProgramImageDetail,
        arguments: WxImagePreviewArgs(
            type: state.imageList[index].fileType,
            fileToken: state.imageList[index].vidFileUrl));
  }

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

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

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

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

  /// 下拉刷新
  Future<void> refreshList() async {
    if (_fullLoadMode) return;
    try {
      _currentPage = 1;
      state.imageList.clear();
      state.imageList = await _getImageUrlsList();
      _totalCount = state.imageList.length;
      state.noData = _totalCount == 0;
      // FIXME remove delay
      await Future.delayed(const Duration(seconds: 1));
    } catch (e) {
      logger.e("refreshList exception:", e);
    }
  }

  /// 获取图像列表
  Future<void> _fetchData() async {
    try {
      state.imageList.addAll(await _getImageUrlsList());
    } catch (e) {
      logger.e("getPatients exception:", e);
    }
  }

  /// 查询图像列表
  Future<List<WxImagesModel>> _getImageUrlsList() async {
    final String openId = Store.user.token;
    List<ImageData> imageDataList = await rpc.appletAPI
        .getRemedicalDataListAsync(GetRemedicalDataListRequest(
      openId: openId,
      remedicalRecordId: _remedicalRecordId,
    ));
    final List<WxImagesModel> result = _imageDataToWxImagesModel(imageDataList);
    return result;
  }

  /// 数据初始化
  void _initData() async {
    final arguments = Get.arguments;
    if (!(arguments is WxImagesListPageArguments)) return;
    if (arguments.dataFetchType == WxImagesListDataFetchType.Full) {
      print("全量载入");
      state.imageList = arguments.imagesList;
      _fullLoadMode = true;
    } else {
      print("分页载入");
      _fullLoadMode = false;
      _currentPage = 1;
      _remedicalRecordId = arguments.remedicalRecordId ?? "";
      state.imageList.clear();
      state.imageList = await _getImageUrlsList();
    }
    _totalCount = state.imageList.length;
    state.noData = _totalCount == 0;
  }

  List<WxImagesModel> _imageDataToWxImagesModel(List<ImageData> imageList) {
    List<WxImagesModel> result = [];
    for (ImageData imageData in imageList) {
      if (imageData.file == null) continue;
      if (imageData.previewFileToken == null) continue;
      if (imageData.file!.fileUrl == null) continue;
      result.add(WxImagesModel(
        previewImageUrl: imageData.previewFileToken!,
        vidFileUrl: imageData.file!.fileUrl!,
        fileType: imageData.dataType == RemedicalFileDataTypeEnum.Image
            ? WxImagesType.SingleFramePng
            : WxImagesType.MultiFrameVid,
      ));
    }
    return result;
  }
}

class WxImagesListPageArguments {
  // 数据载入方式
  final WxImagesListDataFetchType dataFetchType;
  // 会诊ID
  final String? remedicalRecordId;
  // 全量数据
  final List<WxImagesModel> imagesList;

  WxImagesListPageArguments({
    this.dataFetchType = WxImagesListDataFetchType.Full,
    this.remedicalRecordId,
    this.imagesList = const [],
  });
}

// 数据载入方式
enum WxImagesListDataFetchType {
  // 全量传入
  Full,
  // 分页查询
  FetchById,
}

class WxImagesModel {
  final String previewImageUrl;
  final String vidFileUrl;
  final WxImagesType fileType;

  WxImagesModel({
    required this.previewImageUrl,
    required this.vidFileUrl,
    required this.fileType,
  });
}

enum WxImagesType {
  // 单帧图像 png
  SingleFramePng,
  // 多帧视频 vid
  MultiFrameVid,
}
