import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';

import '../shared/tools/sc_path_utils.dart';
import '../ui_kit/components/sc_tts.dart';

class ImagePick {
  static final ImagePicker _picker = ImagePicker();

  /// 选择图片和视频
  static Future<List<File>?> pickPicAndVideoFromGallery(
    BuildContext context,
  ) async {
    try {
      // 调用 pickImage 方法，source 设置为 gallery 即可调用相册
      final XFile? pickedFile = await _picker.pickMedia(
        // 以下为可选参数，用于控制输出图像
        maxWidth: 1800, // 限制图片最大宽度
        maxHeight: 1800, // 限制图片最大高度
        imageQuality: 85, // 图片压缩质量 (0-100)
      );
      if (pickedFile != null) {
        if (!SCPathUtils.fileTypeIsPicAndMP4(pickedFile.path)) {
          SCTts.show( "Please select sc_images in .jpg, .jpeg, .png format.");
          return null;
        }
        return [File(pickedFile.path)];
      }
      return null;
    } catch (e) {
      // 处理异常，例如权限被拒绝或选择器被取消
      print("图片选择出错: $e");
      // 可以在这里添加用户友好的提示信息
      return null;
    }
  }

  /// 从相册选择多张图片
  static Future<List<File>?> pickMultipleFromGallery(
    BuildContext context,
  ) async {
    try {
      final List<XFile> pickedFiles = await _picker.pickMultiImage(
        maxWidth: 1800,
        maxHeight: 1800,
        imageQuality: 85,
        limit: 9,
      );
      if (pickedFiles.isNotEmpty) {
        return pickedFiles
            .where((file) {
              return file.mimeType?.startsWith('image/') == true;
            })
            .map((xFile) => File(xFile.path))
            .toList();
      }
      return null;
    } catch (e) {
      print("多图选择出错: $e");
      return null;
    }
  }

  /// 从相册选择单张图片
  static Future<File?> pickSingleFromGallery(BuildContext context) async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1800,
        maxHeight: 1800,
        imageQuality: 85,
      );
      if (pickedFile != null) {
        if (!SCPathUtils.fileTypeIsPic(pickedFile.path)) {
          SCTts.show( "Please select sc_images in .jpg, .jpeg, .png format.");
          return null;
        }
        return File(pickedFile.path);
      }
      return null;
    } catch (e) {
      print("图片选择出错: $e");
      return null;
    }
  }

  /// 使用相机拍摄照片
  static Future<File?> pickFromCamera(BuildContext context) async {
    try {
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1800,
        maxHeight: 1800,
        imageQuality: 85,
      );
      if (pickedFile != null) {
        return File(pickedFile.path);
      }
      return null;
    } catch (e) {
      print("相机拍照出错: $e");
      return null;
    }
  }
}
