import 'dart:io';

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

import '../resource/colors.gen.dart';
import '../resource/string.gen.dart';

/// 本地选择图片工具类
class ImagePickerUtil {
  static final Color _themeColor = ColorName.colorBrand;

  /// 选择图片
  static Future<List<AssetEntity>> pickImage(
    BuildContext context, {
    required int maxAssetsCount,
    List<AssetEntity> selectedAssets = const [],
  }) async {
    return await AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            // 最大选择数量
            maxAssets: maxAssetsCount,
            // 已选择的图片列表
            selectedAssets: selectedAssets,
            // 自定义按钮文字
            textDelegate: const CustomChineseDelegate(),
            // 主题
            pickerTheme: AssetPicker.themeData(
              // 主题色
              _themeColor,
              // 深色默认
              light: false,
            ),
            // 设置为不能预览的模式
            specialPickerType: SpecialPickerType.noPreview,
            // 只能选取图片类型
            requestType: RequestType.image,
            // 关闭拽托选择
            dragToSelect: false,
            // 实现最近相册的名字显示
            pathNameBuilder:
                (AssetPathEntity path) => switch (path) {
                  final p when p.isAll => StringName.recently,
                  _ => path.name,
                },
          ),
        ) ??
        [];
  }

  /// 跳转到图片预览
  static Future<List<AssetEntity>> goImagePreview(
    BuildContext context,
    List<AssetEntity> previewAssets,
    int index,
  ) async {
    final List<AssetEntity> result =
        await AssetPickerViewer.pushToViewer(
          context,
          // 当前预览的索引位置
          currentIndex: index,
          // 资源列表
          previewAssets: previewAssets,
          // 主题色
          themeData: AssetPicker.themeData(_themeColor),
        ) ??
        [];
    return result;
  }

  /// AssetEntity实体，转换为File列表
  /// [assetsList] 图片、视频选择后的资源列表
  static Future<List<File>> convertAssetToFile(
    List<AssetEntity> assetsList,
  ) async {
    List<File> files = [];

    for (var asset in assetsList) {
      final file = await asset.file;
      if (file != null) {
        files.add(file);
      }
    }

    return files;
  }
}

/// 自定义按钮文字
class CustomChineseDelegate extends AssetPickerTextDelegate {
  const CustomChineseDelegate();

  @override
  String get confirm => StringName.nextStep;
}
