import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';

class UpgradeUtil {
  static Future<void> downloadAndInstallAPK(BuildContext context, String url) async {
    // final permissionStatus = await Permission.storage.request();
    // if (!permissionStatus.isGranted) {
    //   WidgetsBinding.instance.addPostFrameCallback((_) {
    //     ScaffoldMessenger.of(context).showSnackBar(
    //       SnackBar(content: Text("存储权限被拒绝")),
    //     );
    //   });
    //   return;
    // }

    final uri = Uri.parse(url);
    final fileName = uri.pathSegments.isNotEmpty ? uri.pathSegments.last : 'wzj.apk';

    // final dir = await getExternalStorageDirectory();
    // final filePath = "${dir!.path}/$fileName";
    final dir = await getTemporaryDirectory();
    final filePath = "${dir.path}/$fileName";

    WidgetsBinding.instance.addPostFrameCallback((_) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) => DownloadProgressDialog(url: url, savePath: filePath),
      );
    });
  }

  static Future<void> launchAppStore(String iosUrl) async {
    if (await canLaunchUrl(Uri.parse(iosUrl))) {
      await launchUrl(Uri.parse(iosUrl), mode: LaunchMode.externalApplication);
    }
  }
}

class DownloadProgressDialog extends StatefulWidget {
  final String url;
  final String savePath;

  const DownloadProgressDialog({super.key, required this.url, required this.savePath});

  @override
  State<DownloadProgressDialog> createState() => _DownloadProgressDialogState();
}

class _DownloadProgressDialogState extends State<DownloadProgressDialog> {
  double _progress = 0.0;

  @override
  void initState() {
    super.initState();
    _startDownload();
  }

  Future<void> _startDownload() async {
    try {
      final dio = Dio();
      await dio.download(
        widget.url,
        widget.savePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            if (!mounted) return;
            setState(() => _progress = received / total);
          }
        },
      );
      if (!mounted) return;
      await InstallPlugin.installApk(
        widget.savePath,
        appId: 'cn.net.wzj.mall',
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("下载失败：$e")));
    } finally {
      if (mounted) {
        Navigator.pop(context);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(
        "下载中...",
        style: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
          color: Colors.black87,
        ),
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          LinearProgressIndicator(value: _progress),
          SizedBox(height: 10),
          Text("${(_progress * 100).toStringAsFixed(0)}%"),
        ],
      ),
    );
  }
}
