import 'dart:io';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:path_provider/path_provider.dart';

import 'attachment_viewer_page.dart';

class CertificateViewerController extends GetxController with BaseControllerMixin {
  late final String title;
  late final List<String> attachments;

  // --- 新增: 状态管理 ---
  /// 用于存储网络PDF的本地路径，key是网络url，value是本地路径
  final RxMap<String, String> localPdfPaths = <String, String>{}.obs;

  /// 用于跟踪每个附件的加载状态，key是网络url
  final RxMap<String, bool> isLoading = <String, bool>{}.obs;

  @override
  String get builderId => "certificateviewer";

  @override
  void onInit() {
    super.onInit();
    title = Get.arguments['title'] ?? '证件详情';
    attachments = List<String>.from(Get.arguments['attachments'] ?? []);

    // --- 新增: 初始化时开始加载所有PDF ---
    _loadAllPdfs();
  }

  /// 遍历所有附件，如果是PDF则进行下载
  void _loadAllPdfs() {
    for (var url in attachments) {
      if (isPdf(url)) {
        _downloadPdf(url);
      }
    }
  }

  /// 下载单个PDF文件
  Future<void> _downloadPdf(String url) async {
    if (url.isEmpty) return;

    // 开始加载
    isLoading[url] = true;

    try {
      final dio = Dio();
      final Directory tempDir = await getTemporaryDirectory();
      final String savePath = '${tempDir.path}/${url.split('/').last}';

      // 检查文件是否已存在，避免重复下载
      if (await File(savePath).exists()) {
        localPdfPaths[url] = savePath;
        isLoading[url] = false;
        return;
      }

      await dio.download(url, savePath);

      // 下载成功后，更新本地路径
      localPdfPaths[url] = savePath;
    } catch (e) {
      print('PDF download error for $url: $e');
      // 出错时也可以更新状态，以便UI显示错误提示
    } finally {
      // 结束加载
      isLoading[url] = false;
    }
  }

  /// 导航到通用的附件查看器页面 (此方法保持不变)
  void openAttachment(String url) {
    if (url.isEmpty) {
      showErrorToast('附件链接无效');
      return;
    }

    Get.to(() => const AttachmentViewerPage(), arguments: {'url': url});
  }

  /// 检查 URL 是否为 PDF (此方法保持不变)
  bool isPdf(String url) {
    return url.toLowerCase().endsWith('.pdf');
  }
}
