/*
 * @Author: XianKaiQun
 * @Date: 2020-07-07 17:43:08
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-07-25 11:36:42
 * @Description: 
 */

import 'package:barcode_scan2/barcode_scan2.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_qr_reader/flutter_qr_reader.dart';
import 'package:image_picker/image_picker.dart' as ImagePickerAS;
// import 'package:permission_handler/permission_handler.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

///二维码扫描相关功能
class WisScanUtil {
  static WisScanUtil instance = WisScanUtil._();
  WisScanUtil._();

  ///相机扫码
  ///[gallery] 可以从相册中获取
  Future<String?> cameraScan({
    bool gallery = true,
    bool enableTorch = false,
  }) async {
    // bool hasCameraPermission = await Permission.camera.isGranted;
    // if (hasCameraPermission) {
    //   return null;
    // }
    // // 显示权限用途说明对话框
    // bool shouldProceed = await showDialog(
    //       context: WNavUtil.instance!.navigatorKey.currentContext!,
    //       builder: (context) => AlertDialog(
    //         title: Text('申请您的相机访问权限'),
    //         content: Text('我们需要访问您的相机以便您可以扫描二维码，查看任务详情等。'),
    //         actions: [
    //           TextButton(
    //             onPressed: () => Navigator.of(context).pop(false),
    //             child: Text('拒绝'),
    //           ),
    //           TextButton(
    //             onPressed: () => Navigator.of(context).pop(true),
    //             child: Text('允许'),
    //           ),
    //         ],
    //       ),
    //     ) ??
    //     false;
    // if (!shouldProceed) {
    //   return null;
    // }
    final has = await WPermissionUtil.getCameraPermission(
      deniedText: '扫描二维码需要获取您的相机权限,是否前往设置？',
    );
    if (!has) {
      return null;
    }
    return await scanFromCamera(enableTorch: enableTorch);
  }

  /// 从相机扫描二维码/条形码
  Future<String?> scanFromCamera({bool enableTorch = false}) async {
    try {
      // 配置扫描选项
      var options = ScanOptions(
        android: const AndroidOptions(
          aspectTolerance: 0.5,
          useAutoFocus: true,
          // 启用手电筒按钮
        ),
        // 允许扫描的码类型
        restrictFormat: [
          BarcodeFormat.qr,
          BarcodeFormat.code128,
          BarcodeFormat.code39
        ],
        // 自定义提示文本
        strings: {
          'cancel': '取消',
          'flash_on': '打开手电筒',
          'flash_off': '关闭手电筒',
        },
        // 自动启用手电筒
        autoEnableFlash: enableTorch,
      );

      // 启动扫描
      var result = await BarcodeScanner.scan(options: options);

      // 返回扫描结果
      if (result.type != ResultType.Cancelled) {
        return result.rawContent;
      }

      return null;
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        // 相机权限被拒绝
        return null;
      } else {
        // 其他错误
        return null;
      }
    } catch (e) {
      // 未知错误
      return null;
    }
  }

  ///从相册中获取图片扫码
  Future<String?> galleryScan({bool enableTorch = false}) async {
    final has = await WPermissionUtil.getPhotoPermission();
    if (has) {
      final file = await ImagePickerAS.ImagePicker()
          .pickImage(source: ImagePickerAS.ImageSource.gallery);
      if (file != null) {
        // 配置扫描选项
        var options = ScanOptions(
          android: const AndroidOptions(
            aspectTolerance: 0.5,
            useAutoFocus: true,
            // 启用手电筒按钮
          ),
          // 允许扫描的码类型
          restrictFormat: [
            BarcodeFormat.qr,
            BarcodeFormat.code128,
            BarcodeFormat.code39
          ],
          // 自定义提示文本
          strings: {
            'cancel': '取消',
            'flash_on': '打开手电筒',
            'flash_off': '关闭手电筒',
          },
          // 自动启用手电筒
          autoEnableFlash: enableTorch,
        );

        // 使用文件路径扫描
        ScanResult result = await BarcodeScanner.scan(options: options);

        // 返回扫描结果
        if (result.type != ResultType.Cancelled) {
          return result.rawContent;
        }
      }
      return null;
    }
    return null;
  }
}
