import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class UpdateDialog extends StatefulWidget {
  final String downloadUrl;

  const UpdateDialog({super.key, required this.downloadUrl});

  @override
  State<UpdateDialog> createState() => _UpdateDialogState();
}

// 打开外部浏览器的方法
Future<void> launchExternalBrowser(String url) async {
  // 检查是否可以启动URL
  if (await canLaunchUrl(Uri.parse(url))) {
    // 启动URL，使用外部浏览器
    await launchUrl(
      Uri.parse(url),
      mode: LaunchMode.externalApplication, // 这会强制使用外部浏览器
    );
  } else {
    // 如果无法启动URL，抛出异常或处理错误
    throw '无法打开 $url';
  }
}

class _UpdateDialogState extends State<UpdateDialog> {
  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      color: const Color(0x1A000000),
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Container(
            width: 307,
            color: Colors.white,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: Image(
                    width: 80,
                    height: 80,
                    image: AssetImage('assets/images/ic_update.png'),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: Text(
                    "有新版本请更新",
                    style: TextStyle(fontSize: 20),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    launchExternalBrowser(widget.downloadUrl);
                  },
                  child: Container(
                    width: 160,
                    height: 50,
                    alignment: Alignment.center,
                    margin: EdgeInsets.symmetric(vertical: 20),
                    decoration: BoxDecoration(color: Colors.lightBlue, borderRadius: BorderRadius.all(Radius.circular(15))),
                    child: Text(
                      "去更新",
                      style: TextStyle(fontSize: 22, color: Colors.white),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
