import 'dart:io';

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

import '../../../../../../common/api/index.dart';
import '../../../../../../common/models/index.dart';
import '../../../../../../common/utils/index.dart';

class ImageLoaderController extends GetxController {
  ImageLoaderController(this.fileInfo);

  final FileInfo fileInfo;

  /// 文件本地地址
  final fileLocalPath = "".obs;

  @override
  void onReady() {
    _loadImageFile();
    super.onReady();
  }


  _loadImageFile() async {
    final fileId = fileInfo.id ?? '';
    if (fileId.isEmpty) {
      OLogger.e('错误的文件对象！');
      return;
    }
    String? filePath = await O2FilePathUtil.getCloudDiskFileDownloadLocalPath(
        fileId, fileInfo.fileNamePlusExtension());
    if (filePath == null || filePath.isEmpty) {
      OLogger.e('错误的文件 路径！');
      return;
    }
    try {
      final file = File(filePath);
      if (!file.existsSync()) {
        // 下载附件
        var donwloadUrl = FileAssembleService.to.fileDownloadUrl(fileId);
        if (fileInfo.isV3) {
          donwloadUrl = FileAssembleService.to.fileDownloadUrlV3(fileId);
        }
        await O2HttpClient.instance.downloadFile(donwloadUrl, filePath);
      }
      fileLocalPath.value = filePath;
      update();
    } on Exception catch (e) {
      OLogger.e('下载文件失败', e);
    }
  }

  Future<void> saveToAlbum() async {
    if (fileLocalPath.value.isNotEmpty) {
      // 测试分享图片
      // final result = await Share.shareXFiles([XFile(fileLocalPath.value)]);
      final result = await O2FlutterMethodChannelUtils().saveToAlbum(fileLocalPath.value);
      if (result) {
        Loading.toast('cloud_disk_save_image_album_success'.tr);
      }
    }
    
  }
 
}
