import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:photo_view/photo_view.dart';

import 'attachment_viewer_controller.dart';

class AttachmentViewerPage extends GetView<AttachmentViewerController> {
  const AttachmentViewerPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(AttachmentViewerController());
    // final fileName = controller.url.split('/').last;

    return Scaffold(
      appBar: AppBar(
        title: Text(
          "证件详情",
          style: const TextStyle(fontSize: 16),
          overflow: TextOverflow.ellipsis,
        ),
        centerTitle: true,
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const CircularProgressIndicator(),
                const SizedBox(height: 20),
                Text(controller.loadingText.value),
              ],
            ),
          );
        }

        if (controller.fileType == 'pdf') {
          if (controller.localFilePath.isNotEmpty) {
            return PDFView(
              filePath: controller.localFilePath.value,
              enableSwipe: true,
              swipeHorizontal: true,
              autoSpacing: true,
              pageFling: true,
              onRender: (pages) {
                print("PDF rendered with $pages pages.");
              },
              onError: (error) {
                print(error.toString());
                showErrorToast('渲染PDF时出错');
              },
              onPageError: (page, error) {
                print('$page: ${error.toString()}');
                 showErrorToast('渲染第$page页时出错');
              },
            );
          } else {
            return const Center(child: Text('无法加载PDF文件'));
          }
        } else {
          return PhotoView(
            imageProvider: NetworkImage(controller.url),
            minScale: PhotoViewComputedScale.contained * 0.8,
            maxScale: PhotoViewComputedScale.covered * 2.0,
            loadingBuilder: (context, event) => const Center(
              child: CircularProgressIndicator(),
            ),
            backgroundDecoration: const BoxDecoration(
              color: Colors.black,
            ),
          );
        }
      }),
    );
  }
}
