import 'dart:async';
import 'dart:io';

import 'package:account_center/widget/file_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';

class PdfPreview extends StatefulWidget {
  final String url;

  /// 临时文件全路径
  final String? tempFilePath;
  const PdfPreview(this.url, {this.tempFilePath, Key? key}) : super(key: key);

  @override
  State<PdfPreview> createState() => _PdfPreviewState();
}

class _PdfPreviewState extends State<PdfPreview> {
  String? filePath;

  @override
  void initState() {
    createFileOfPdfUrl().then((file) {
      Future.delayed(const Duration(milliseconds: 200)).then((value) {
        setState(() {
          filePath = file.path;
        });
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return filePath == null
        ? const Center(
            child: CircularProgressIndicator(),
          )
        : PDFView(filePath: filePath);
  }

  Future<File> createFileOfPdfUrl() async {
    Completer<File> completer = Completer();
    try {
      final url = widget.url;
      String? filePath = widget.tempFilePath;
      if (filePath == null) {
        final filename = getTempDownloadName(url);
        var dir = await getApplicationDocumentsDirectory();
        filePath = "${dir.path}/$filename";
      }
      File file = File(filePath);
      if (!file.existsSync()) {
        var request = await HttpClient().getUrl(Uri.parse(url));
        var response = await request.close();
        var bytes = await consolidateHttpClientResponseBytes(response);
        await file.writeAsBytes(bytes, flush: true);
      }
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file!');
    }
    return completer.future;
  }
}
