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';

class AttachmentViewerController extends GetxController {
  late final String url;
  late final String fileType;

  final RxBool isLoading = true.obs;
  final RxString localFilePath = ''.obs;
  final RxString loadingText = '加载中...'.obs;

  @override
  void onInit() {
    super.onInit();
    url = Get.arguments['url'] ?? '';
    if (url.isEmpty) {
      showErrorToast('无效的附件链接');
      Get.back();
      return;
    }

    if (url.toLowerCase().endsWith('.pdf')) {
      fileType = 'pdf';
      _downloadPdf();
    } else {
      fileType = 'image';
      isLoading.value = false;
    }
  }

  Future<void> _downloadPdf() async {
    try {
      final dio = Dio();
      final tempDir = await getTemporaryDirectory();
      final fileName = '${DateTime.now().millisecondsSinceEpoch}_${url.split('/').last}';
      final savePath = '${tempDir.path}/$fileName';

      await dio.download(
        url,
        savePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            loadingText.value = '下载中...${(received / total * 100).toStringAsFixed(0)}%';
          }
        },
      );

      localFilePath.value = savePath;

    } catch (e) {
      showErrorToast('PDF文件加载失败，请检查网络或文件链接');
      print('PDF Download Error: $e');
      Get.back();
    } finally {
      isLoading.value = false;
    }
  }
}
