import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../Image_slider_viewer/index.dart';
import '../cloud_disk_helpler.dart';
import 'index.dart';

class FileTypeListController extends GetxController {
  FileTypeListController();

  final state = FileTypeListState();
 
  final refreshController = RefreshController();
  int page = 1; // 分页查询
  bool isLoading = false; // 防止重复刷新

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null && map['type'] != null && map['type'] is CloudDiskFileType) {
      state.type.value = map['type'];
    }
    refreshFileList();
    super.onReady();
  }
 
  /// 刷新列表
  refreshFileList() async {
    if (isLoading) return;
    page = 1;
    isLoading = true;
    state.fileList.clear();
    final result = await FileAssembleService.to.listFileByType(state.type.value.getKey(), page);
    if (result != null ) {
      state.fileList.addAll(result);
    }
    refreshController.refreshCompleted();
    state.hasMoreData = (result?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  /// 加载更多
  loadMoreFileList() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isLoading = true;
    page++;
    final result = await FileAssembleService.to.listFileByType(state.type.value.getKey(), page);
    if (result != null ) {
      state.fileList.addAll(result);
    }
    refreshController.loadComplete();
    state.hasMoreData = (result?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }
  
  /// 在线图片地址
  String imageOnlineUrl(String? fileId, double w, double h) {
    if (fileId == null || fileId.isEmpty) {
      return "";
    }
    return FileAssembleService.to.imageFileUrl(fileId, w.toInt(), h.toInt());
  }
  /// 
  Map<String, String> getHeaders() {
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    return headers;
  }


  void clickFile(FileInfo file) {
    if (file.fileNamePlusExtension().isImageFileName == true) {
      final imageList = state.fileList.where((p0) => p0.fileNamePlusExtension().isImageFileName == true).map((e) {
        FileInfo info = e;
        info.isV3 = false;
        return info;
      }).toList();
      ImageSliderViewerPage.openViewer(imageList, currentFileId: file.id);
    } else {
      CloudDiskHelper().downloadAndOpenFile(file);
    }
  }
}
