/*
 * @Author: XianKaiQun
 * @Date: 2020-08-31 11:45:11
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-25 11:39:50
 * @Description: 
 */

import 'dart:async';
import 'dart:io' as IOPlatfrom;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_picker_platform_interface/src/types/image_source.dart'
    as Isource;
import 'package:permission_handler/permission_handler.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

import '../views/album_view.dart';
export '../views/album_view.dart' show FileEntity;

///图片选择来源
///
///[camera]相机，
///[gallery]相册，
///[cameraAndGallery]和相册
enum WImageSource { camera, gallery, cameraAndGallery }

///静态资源选择器
class WAssetPickerUtil {
  WAssetPickerUtil._();

  ///获取相册权限
  static Future<bool> getPhotoPermission() async {
    if (IOPlatfrom.Platform.isAndroid) {
      bool permission = await WPermissionUtil.getPhotoPermission();
      if (permission) {
        return true;
      } else {
        final confirm = await (WModalUtil.showSync(
          '无法获取相机权限,是否前往设置',
          title: '权限申请失败',
          confirmText: '前往设置',
        ) as Future<bool>);
        if (confirm) {
          await openAppSettings();
          bool permission = await WPermissionUtil.getPhotoPermission();
          return permission;
        }
      }
      return false;
    } else {
      bool isSuccess = await Permission.photos.request().isGranted;
      if (isSuccess) {
        return true;
      } else {
        final confirm = await (WModalUtil.showSync(
          '无法获取相机权限,是否前往设置',
          title: '权限申请失败',
          confirmText: '前往设置',
        ) as Future<bool>);
        if (confirm) {
          await openAppSettings();
          bool permission = await Permission.photos.request().isGranted;
          return permission;
        }
      }
    }

    return false;
  }

  /// 拍照或者从相机中选择
  /// [maxCount]最大选择数目，
  /// [source]  图片来源
  /// [sourceCallBack] 回调图片来源（相机或相册）
  static Future<List<FileEntity>> image({
    int maxCount = 9,
    WImageSource source = WImageSource.cameraAndGallery,
    void Function(WImageSource source)? sourceCallBack,
  }) async {
    final completer = Completer<List<FileEntity>>();

    ///相机
    Future<List<FileEntity>?> _camera() async {
      if (!await WPermissionUtil.getCameraPermission()) return null;
      final res = await ImagePicker().pickImage(
        source: Isource.ImageSource.camera,
        imageQuality: 50,
      );
      if (res == null) return null;
      if (sourceCallBack != null) sourceCallBack(WImageSource.camera);
      return [FileEntity(file: IOPlatfrom.File(res.path))];
    }

    ///相册
    Future<List<FileEntity>?> _gallery() async {
      bool isOk = await WPermissionUtil.getPhotoPermission();

      if (!isOk) return null;
      if (sourceCallBack != null)
        sourceCallBack(
          WImageSource.gallery,
        );
      return WAlbumView.pushRoute(maxCount: maxCount);
    }

    switch (source) {
      case WImageSource.camera:
        completer.complete(await _camera());
        break;
      case WImageSource.gallery:
        completer.complete(await _gallery());
        break;
      default:

        ///默认两个都可以（弹出action选择）
        _ImagePickerActionSheet.show(
          onCameraTap: () async => completer.complete(await _camera() ?? []),
          onGalleryTap: () async => completer.complete(await _gallery() ?? []),
          onCancelTap: () => completer.complete([]),
        );
    }

    return completer.future;
  }
}

///弹出层样式
///
///
///
///
class _ImagePickerActionSheet extends StatelessWidget {
  const _ImagePickerActionSheet({
    Key? key,
    this.onCameraTap,
    this.onGalleryTap,
    this.onCancelTap,
  }) : super(key: key);
  final Function()? onCameraTap;
  final Function()? onGalleryTap;
  final Function()? onCancelTap;

  static Future<void> show({
    Function()? onCameraTap,
    Function()? onGalleryTap,
    Function()? onCancelTap,
  }) {
    return WNavUtil.instance!.showModalBottomSheet(
      backgroundColor: Color(0xfff7f7f7),
      builder: (_) => _ImagePickerActionSheet(
        onCameraTap: onCameraTap,
        onGalleryTap: onGalleryTap,
        onCancelTap: onCancelTap,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: ListTile.divideTiles(
          context: context,
          tiles: [
            Wisdom(
              onTap: () {
                Navigator.pop(context);
                onCameraTap!();
              },
              alignment: Alignment.center,
              color: Colors.white,
              height: 44.pt,
              child: Text('拍照'),
            ),
            Wisdom(
              onTap: () {
                Navigator.pop(context);
                onGalleryTap!();
              },
              alignment: Alignment.center,
              color: Colors.white,
              height: 44.pt,
              child: Text('从相册选择'),
            ),
            Wisdom(
              onTap: () {
                Navigator.pop(context);
                onCancelTap!();
              },
              margin: EdgeInsets.only(top: 15.pt),
              alignment: Alignment.center,
              color: Colors.white,
              height: 44.pt,
              child: Text('取消'),
            ),
          ],
        ).toList(),
      ),
    );
  }
}



