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

class AppUpgradeService {
  final Dio _dio = Dio();
  
  /// 下载更新文件
  Future<String?> downloadUpdate(String url, Function(double) onProgress) async {
    try {
      // 获取临时目录
      final tempDir = await getTemporaryDirectory();
      final savePath = '${tempDir.path}/app_update.apk';
      
      // 下载文件
      await _dio.download(
        url,
        savePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            onProgress(received / total);
          }
        },
      );
      
      return savePath;
    } catch (e) {
      print('下载更新失败: $e');
      return null;
    }
  }
  
  /// 安装更新
  Future<bool> installUpdate(String filePath) async {
    try {
      if (Platform.isAndroid) {
        // 对于Android，需要使用intent打开APK文件
        final uri = Uri.file(filePath);
        if (await canLaunchUrl(uri)) {
          return await launchUrl(uri);
        }
      } else if (Platform.isIOS) {
        // 对于iOS，通常是打开App Store
        final appStoreUrl = Uri.parse('https://apps.apple.com/app/yourappid');
        if (await canLaunchUrl(appStoreUrl)) {
          return await launchUrl(appStoreUrl);
        }
      }
      return false;
    } catch (e) {
      print('安装更新失败: $e');
      return false;
    }
  }
  
  /// 显示更新对话框
  Future<bool> showUpdateDialog(BuildContext context, Map<String, dynamic> updateInfo) async {
    return await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('发现新版本 ${updateInfo['version']}'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('当前版本: ${updateInfo['currentVersion']}'),
            const SizedBox(height: 8),
            Text('更新内容:'),
            const SizedBox(height: 4),
            Text(updateInfo['description'] ?? '优化了用户体验'),
          ],
        ),
        actions: [
          if (updateInfo['forceUpdate'] != true)
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('稍后再说'),
            ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('立即更新'),
          ),
        ],
      ),
    );
  }
}