import 'package:image_picker/image_picker.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/album_default_select_dialog.dart';

import '../permission/permission_engine.dart';
import '../dialog/dialog_engine.dart';
import 'album_engine.dart';
import 'camera_engine.dart';


/*
    相机相册选择的封装

    1.相机相册的选择弹框
    2.相机相册权限提示详情描述弹窗
    3.调用相机相册的引擎封装类 CameraEngine  AlbumEngine  ImageCropEngine 的使用
 */
class ImagePickerUtils {
  // 私有构造函数
  ImagePickerUtils._privateConstructor();

  // 单例实例
  static final ImagePickerUtils _instance = ImagePickerUtils._privateConstructor();

  // 获取单例实例的访问点
  factory ImagePickerUtils() {
    return _instance;
  }

  /// 入口
  void show({
    required void Function(List<String?> filePaths) complete,
    int maxAssets = 1,
  }) {
    DialogEngine.show(
        position: DialogPosition.bottom,
        widget: AlbumDefaultSelectDialog(cameraAction: () {
          //相机权限
          PermissionEngine().requestCameraPermission(() {
            //调用相机引擎读取图片
            pickFormCamera(
              complete: (filePath) {
                complete(filePath);
              },
            );
          });
        }, albumAction: () {
          //调用相册引擎读取图片
          pickFormAlbum(
            complete: (filePath) {
              complete(filePath);
            },
            maxAssets: maxAssets,
          );
        }));
  }

  /// 从摄像头拍摄
  void pickFormCamera({
    required void Function(List<String?> filePaths) complete,
    bool isCropped = false,
    double aspectRatio = 1.0,
  }) async {
    final XFile? xFile = await CameraEngine.takePhoto();
    Log.d("从摄像头拍摄路径：${xFile?.path}");

    complete([xFile?.path]);
  }

  /// 从相册中选择
  void pickFormAlbum({
    required void Function(List<String?> filePaths) complete,
    int maxAssets = 1,
  }) async {
    //多选与单选
    if (maxAssets > 1) {
      final List<XFile?>? xFiles = await AlbumEngine.selectMultiImage();
      if (xFiles != null) {
        final filePaths = xFiles.where((e) => e != null && e.path.isNotEmpty).map((e) => e!.path).toList();

        //如果 filePaths 的长度大于 maxAssets 那么只取前maxAssets个数量
        if (filePaths.length > maxAssets) {
          filePaths.removeRange(maxAssets, filePaths.length);
        }
        //多选没有裁剪判断逻辑
        complete(filePaths);
      } else {
        complete([]);
      }
    } else {
      //单选中会判断是否触发裁剪
      final XFile? xFile = await AlbumEngine.selectImage();
      Log.d("从相册单选路径：${xFile?.path}");

      complete([xFile?.path]);
    }
  }
}
