import 'dart:io';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

class ApkInstaller {
  static const _platform = MethodChannel('apk_installer_channel');

  /// 安装 APK 文件
  static Future<void> installApk(String apkPath) async {
    try {
      // 检查文件是否存在
      final file = File(apkPath);
      if (!await file.exists()) {
        throw Exception('APK 文件不存在: $apkPath');
      }

      // 检查安装权限
      if (Platform.isAndroid) {
        if (await _checkInstallPermission()) {
          await _installApkAndroid(apkPath);
        }
      }
    } catch (e) {
      throw Exception('安装失败: $e');
    }
  }

  /// 检查并请求安装权限
  static Future<bool> _checkInstallPermission() async {
    if (Platform.isAndroid) {
      // 检查是否有安装权限
      if (await Permission.requestInstallPackages.isGranted) {
        return true;
      }

      // 请求权限
      final status = await Permission.requestInstallPackages.request();
      return status.isGranted;
    }
    return false;
  }

  /// 在 Android 上安装 APK
  static Future<void> _installApkAndroid(String apkPath) async {
    try {
      final Map<String, dynamic> args = {'apkPath': apkPath};
      await _platform.invokeMethod('installApk', args);
    } on PlatformException catch (e) {
      throw Exception('安装失败: ${e.message}');
    }
  }
}