import 'dart:async';

import 'package:ai_barcode_scanner/ai_barcode_scanner.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class ScanUtil {
  static Future<void> openScanner({required void Function(String) onResult}) async {
    final controller = MobileScannerController();
    bool hasHandled = false;

    bool validator(BarcodeCapture capture) {
      final code = capture.barcodes.isNotEmpty ? capture.barcodes.first.rawValue : null;
      return code != null && code.isNotEmpty;
    }

    final result = await Get.to<String>(
      () => AiBarcodeScanner(
        controller: controller,
        galleryButtonText: '从相册选择',
        galleryButtonAlignment: const Alignment(0.0, 0.7),
        validator: validator,
        onDetect: (capture) {
          if (hasHandled) return;
          final code = capture.barcodes.isNotEmpty ? capture.barcodes.first.rawValue : null;
          if (code != null && code.isNotEmpty) {
            hasHandled = true;
            Get.back(result: code);
          }
        },
        overlayConfig: const ScannerOverlayConfig(
          scannerBorder: ScannerBorder.corner,
          borderColor: Colors.greenAccent,
          successColor: Colors.lightGreenAccent,
          errorColor: Colors.redAccent,
          borderRadius: 24,
          cornerLength: 60,
          scannerAnimation: ScannerAnimation.fullWidth,
        ),
        scanWindow: Rect.fromCenter(
          center: MediaQuery.of(Get.context!).size.center(Offset.zero),
          width: MediaQuery.of(Get.context!).size.width * 0.8,
          height: MediaQuery.of(Get.context!).size.height * 0.5,
        ),
        // 异常处理
        errorBuilder: (context, error) {
          String message = "无法启动摄像头，请检查权限";
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.error, color: Colors.red, size: 60),
                const SizedBox(height: 16),
                Text(
                  message,
                  style: const TextStyle(fontSize: 18, color: Colors.red),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 8),
                ElevatedButton(
                  onPressed: () async => await openAppSettings(),
                  child: const Text('去开启权限'),
                ),
              ],
            ),
          );
        },
      ),
    );

    if (result != null && result.isNotEmpty) {
      onResult(result);
    }
  }
}
