import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class AttachmentWebViewer extends StatefulWidget {
  final String fileUrl;     // 文件的网络地址
  final String fileName;    // 显示在 AppBar 上的名称（可选）

  const AttachmentWebViewer({
    super.key,
    required this.fileUrl,
    this.fileName = '附件预览',
  });

  @override
  State<AttachmentWebViewer> createState() => _AttachmentWebViewerState();
}

class _AttachmentWebViewerState extends State<AttachmentWebViewer> {
  late final WebViewController _controller;
  bool _isLoading = true;

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

    // 初始化 WebView 控制器
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onPageFinished: (_) => setState(() => _isLoading = false),
      ))
      ..loadRequest(Uri.parse(_buildPreviewUrl(widget.fileUrl)));
  }

  /// 构造预览链接（pdf 直接打开，其它用 Google Docs）
  String _buildPreviewUrl(String url) {
    final lower = url.toLowerCase();
    if (lower.endsWith('.pdf')) {
      return url;
    } else {
      return 'https://docs.google.com/gview?embedded=true&url=$url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.fileName)),
      body: Stack(
        children: [
          WebViewWidget(controller: _controller),
          if (_isLoading)
            const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }
}
