import 'dart:io';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'package:vbvs_app/common/color/appConstants.dart';

class UserPdfController extends GetxController {
  var localPdfPath = Rx<String?>(null);

  // 加载 PDF 文件
  Future<void> loadPdf(int type, [String? url]) async {
    final tempDir = await getTemporaryDirectory();
    final filename = type == 1 ? 'service.pdf' : 'privacy.pdf';
    final filePath = p.join(tempDir.path, filename);
    final file = File(filePath);

    try {
      if (url == null || url.isEmpty) {
        final byteData = await rootBundle
            .load(type == 1 ? 'assets/img/服务协议.pdf' : 'assets/img/隐私协议.pdf');
        await file.writeAsBytes(byteData.buffer.asUint8List());
      } else {
        final response = await http.get(Uri.parse(url));
        if (response.statusCode == 200) {
          await file.writeAsBytes(response.bodyBytes);
        } else {
          throw Exception('【PDF加载】类型$type：无法下载 PDF，状态码 ${response.statusCode}');
        }
      }
    } catch (e) {
      final byteData = await rootBundle
          .load(type == 1 ? 'assets/img/服务协议.pdf' : 'assets/img/隐私协议.pdf');
      await file.writeAsBytes(byteData.buffer.asUint8List());
    }

    localPdfPath.value = filePath;
  }
}
