import 'package:flutter/material.dart';
import 'package:in_app_review/in_app_review.dart';
import 'package:url_launcher/url_launcher.dart';

class AppReviewService {
  static final InAppReview _inAppReview = InAppReview.instance;
  static const String _appStoreId = '6743112546'; // 替换为你的App Store ID

  // 触发评价逻辑
  static Future<void> requestAppReview(BuildContext context) async {
    try {
      bool isAvailable = await _inAppReview.isAvailable();
      if (isAvailable) {
        // 尝试显示应用内评分
        await _inAppReview.requestReview();
      } else {
        // 不可用时直接跳转到App Store
        await _launchAppStore();
      }
    } catch (e) {
      // 任何错误都跳转到App Store
      await _launchAppStore();
      ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已为您打开应用商店评价页面'))
      );
      print('Error requesting review: $e');
    }
  }

  // 使用url_launcher直接打开App Store
  static Future<void> _launchAppStore() async {
    final url = Uri.parse('https://apps.apple.com/app/id$_appStoreId');
    if (await canLaunchUrl(url)) {
      await launchUrl(url, mode: LaunchMode.externalApplication);
    }
  }

  // 直接打开应用商店（备用方法）
  static Future<void> openStoreReview(BuildContext context) async {
    await _launchAppStore();
  }
}
