import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:widgets/dialog/album_default_select_dialog.dart';

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

/*
    相机相册选择的封装

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

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

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

  /// 入口
  void show(
    BuildContext context,
    void Function(String filePath) complete, {
    bool isCropped = false,
    CropAspectRatioPreset aspect = CropAspectRatioPreset.square,
  }) {
    DialogEngine.show(
        position: DialogPosition.bottom,
        widget: AlbumDefaultSelectDialog(cameraAction: () {
          //相机的选项
          PermissionEngine().requestCameraPermission(() {
            //调用相机引擎读取图片
            _selectFormCamera(context, (filePath) {
              complete(filePath);
            }, isCropped: isCropped, aspect: aspect);
          });
        }, albumAction: () {
          //相册的选项
          PermissionEngine().requestPhotosPermission(() {
            //调用相册引擎读取图片
            _selectFormAlbum(context, (filePath) {
              complete(filePath);
            }, isCropped: isCropped, aspect: aspect);
          });
        }));
  }

  /// 从相机中选择
  Future _selectFormCamera(
    BuildContext context,
    void Function(String filePath) complete, {
    bool isCropped = false,
    CropAspectRatioPreset aspect = CropAspectRatioPreset.square,
  }) async {
    final AssetEntity? result = await CameraEngine.takePhoto(context);

    if (result != null) {
      final file = await result.file;
      final filePath = file?.path;

      if (filePath != null && isCropped == true) {
        final croppedPath = await ImageCropEngine.imageCrop(context, filePath, aspect: aspect);
        complete(croppedPath!);
      } else {
        complete(filePath!);
      }
    }
  }

  /// 从相册中选择
  Future _selectFormAlbum(
    BuildContext context,
    void Function(String filePath) complete, {
    bool isCropped = false,
    CropAspectRatioPreset aspect = CropAspectRatioPreset.square,
  }) async {
    final List<AssetEntity>? result = await AlbumEngine.selectImage(context, maxAssets: 1);
    if (result != null && result.isNotEmpty) {
      final file = await result[0].file;
      final filePath = file?.path;

      if (filePath != null && isCropped == true) {
        final croppedPath = await ImageCropEngine.imageCrop(context, filePath, aspect: aspect);
        complete(croppedPath!);
      } else {
        complete(filePath!);
      }
    }
  }
}
