import 'package:get/get.dart';
import 'package:kaer_with_panels/app/services/api_service/kr_subscribe_api.dart';
import 'package:kaer_with_panels/app/model/response/kr_package_list.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../../common/app_run_data.dart';
import '../../../common/app_config.dart';
import '../../../model/response/kr_already_subscribe.dart';
import '../../../model/response/kr_payment_methods.dart';
import '../../../routes/app_pages.dart';
import '../../../services/api_service/kr_api.user.dart';
import '../../../utils/kr_event_bus.dart';
import '../../../network/http_util.dart';
import 'package:flutter/foundation.dart';
// import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/store_kit_2_wrappers.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:kaer_with_panels/app/model/response/kr_purchase_order_no.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/hi_dialog.dart';
import 'package:kaer_with_panels/app/services/iap/iap_pending_order_service.dart';
import 'package:kaer_with_panels/app/services/iap/iap_service.dart';
import '../../../services/kr_site_config_service.dart';

/// 会员购买控制器
/// 负责处理会员套餐选择、支付方式选择和订阅流程
class KRPurchaseMembershipController extends GetxController {
  // 注入的服务
  final KRSubscribeApi _kr_subscribeApi = KRSubscribeApi();

  // 事件监听器
  Worker? _kr_eventWorker;

  // UI 状态
  final RxBool kr_isLoading = false.obs;
  final RxString kr_errorMessage = ''.obs;
  final RxString kr_userEmail = ''.obs;
  final RxBool kr_showPlanSelector = false.obs; // 是否显示套餐选择器

  // 数据状态
  final RxList<KRPackageListItem> kr_plans = <KRPackageListItem>[].obs;
  final RxList<KRPaymentMethod> kr_paymentMethods = <KRPaymentMethod>[].obs;
  final RxInt kr_selectedPlanIndex = 0.obs;
  final RxInt kr_selectedPaymentMethodIndex = (-1).obs;
  final RxInt kr_selectedDiscountIndex = (-1).obs;

  // 已订阅套餐列表
  var _kr_alreadySubscribe = <KRAlreadySubscribe>[];

  /// 描述是否展开
  final kr_isDescriptionExpanded = false.obs;

  /// 当前余额
  RxInt _kr_balance = 0.obs;

  @override
  void onInit() async {
    super.onInit();
    // 预热客服
    KRCommonUtil.kr_warmUpCustomerService();
    print(
        '💳 [PurchaseMembership] ========== Controller.onInit 被调用 ==========');
    print('💳 [PurchaseMembership] 当前时间: ${DateTime.now()}');

    // 🔧 紧急诊断：写文件确认购买页面Controller被初始化
    try {
      final dir = await getApplicationDocumentsDirectory();
      final debugFile = File('${dir.path}/PURCHASE_CONTROLLER_DEBUG.txt');
      await debugFile.writeAsString(
        '=' * 60 +
            '\n'
                    '💳 PurchaseMembershipController.onInit 被调用!\n'
                    '时间: ${DateTime.now()}\n'
                    '版本标识: Android15_Fix_v6_Final\n'
                    '=' *
                60 +
            '\n',
        mode: FileMode.append,
      );
      print('💳 [PurchaseMembership] ✅ 调试日志已写入文件: ${debugFile.path}');
    } catch (e) {
      print('💳 [PurchaseMembership] ❌ 写入调试日志失败: $e');
    }

    // 判断是否有 curversion，如果没有先请求下 site/config 接口让配置初始化下
    final siteConfigService = KRSiteConfigService();
    if (siteConfigService.getCurVersion().isEmpty) {
      siteConfigService.fetchSiteConfig();
    }

    kr_initializeData();
  }

  @override
  void onClose() {
    _kr_eventWorker?.dispose();
    super.onClose();
  }

  /// 初始化数据
  Future<void> kr_initializeData() async {
    print('💳 [PurchaseMembership] initializeData 开始');
    kr_userEmail.value = KRAppRunData.getInstance().kr_account.toString();
    print('💳 [PurchaseMembership] 用户邮箱: ${kr_userEmail.value}');

    // 🔧 关键修复：不要在 onInit 中 await，让页面先显示，数据异步加载
    // 这样可以避免 API 请求卡住导致页面无法显示
    print('💳 [PurchaseMembership] 开始异步加载套餐数据...');
    kr_getPackageList().catchError((e) {
      print('💳 [PurchaseMembership] ❌ 加载套餐数据异常: $e');
      KRLogUtil.kr_e('加载套餐数据失败: $e', tag: 'PurchaseMembership');
    });

    // 监听所有支付相关消息
    _kr_eventWorker = KREventBus().kr_listenMessages(
      [KRMessageType.kr_payment, KRMessageType.kr_subscribe_update],
      _kr_handleMessage,
    );
    print('💳 [PurchaseMembership] initializeData 完成');
  }

  /// 处理消息
  Future<void> _kr_handleMessage(KRMessageData message) async {
    switch (message.kr_type) {
      case KRMessageType.kr_payment:
        await _iniUserInfo();
        // 只更新支付方式显示，因为支付方式标题中包含余额信息
        if (kr_paymentMethods.isNotEmpty) {
          final balanceMethodIndex = kr_paymentMethods
              .indexWhere((method) => method.platform == 'balance');
          if (balanceMethodIndex != -1) {
            // 触发支付方式列表更新
            kr_paymentMethods.refresh();
          }
        }
        break;
      case KRMessageType.kr_subscribe_update:
        break;
      default:
        break;
    }
  }

  /// 获取套餐列表和支付方式
  Future<void> kr_getPackageList() async {
    print('💳 [PurchaseMembership] ========== 开始获取套餐列表 ==========');
    print('💳 [PurchaseMembership] 当前时间: ${DateTime.now()}');

    kr_isLoading.value = true;
    kr_selectedPlanIndex.value = 0; // 重置套餐选择
    kr_selectedDiscountIndex.value = -1; // 重置折扣选择
    kr_selectedPaymentMethodIndex.value = -1; // 重置支付方式选择

    try {
      // 🔧 添加超时保护，避免 API 请求卡死
      print('💳 [PurchaseMembership] 步骤1: 开始初始化用户信息...');
      await _iniUserInfo().timeout(
        const Duration(seconds: 5),
        onTimeout: () {
          print('💳 [PurchaseMembership] ⚠️ 初始化用户信息超时');
          KRLogUtil.kr_w('初始化用户信息超时', tag: 'PurchaseMembership');
        },
      );
      print('💳 [PurchaseMembership] ✓ 步骤1完成');

      print('💳 [PurchaseMembership] 步骤2: 开始获取已订阅套餐...');
      await kr_getAlreadySubscribe().timeout(
        const Duration(seconds: 5),
        onTimeout: () {
          print('💳 [PurchaseMembership] ⚠️ 获取已订阅套餐超时');
          KRLogUtil.kr_w('获取已订阅套餐超时', tag: 'PurchaseMembership');
        },
      );
      print('💳 [PurchaseMembership] ✓ 步骤2完成');

      print('💳 [PurchaseMembership] 步骤3: 开始获取套餐列表...');
      await kr_fetchPackages().timeout(
        const Duration(seconds: 8),
        onTimeout: () {
          print('💳 [PurchaseMembership] ❌ 获取套餐列表超时');
          KRLogUtil.kr_e('获取套餐列表超时', tag: 'PurchaseMembership');
          KRCommonUtil.kr_showToast('获取套餐列表超时，请检查网络');
        },
      );
      print('💳 [PurchaseMembership] ✓ 步骤3完成，套餐数量: ${kr_plans.length}');

      // 获取公开的支付方式
      print('💳 [PurchaseMembership] 步骤4: 开始获取支付方式...');
      await _kr_fetchPublicPaymentMethods().timeout(
        const Duration(seconds: 5),
        onTimeout: () {
          print('💳 [PurchaseMembership] ⚠️ 获取支付方式超时');
          KRLogUtil.kr_w('获取支付方式超时', tag: 'PurchaseMembership');
        },
      );
      print(
          '💳 [PurchaseMembership] ✓ 步骤4完成，支付方式数量: ${kr_paymentMethods.length}');

      // 根据套餐数量决定是否显示套餐选择器
      kr_showPlanSelector.value = kr_plans.length > 1;
      print('💳 [PurchaseMembership] ========== 所有步骤完成 ==========');
    } catch (e, stackTrace) {
      print('💳 [PurchaseMembership] ❌❌❌ 获取套餐数据失败: $e');
      print('💳 [PurchaseMembership] StackTrace: $stackTrace');
      KRLogUtil.kr_e('获取套餐数据失败: $e', tag: 'PurchaseMembership');

      // 🔧 关键修复：API失败时,尝试切换域名并重试
      print('💳 [PurchaseMembership] 🔄 尝试切换域名并重试...');
      bool domainSwitched = await KRDomain.kr_switchToNextDomain();

      if (domainSwitched) {
        print(
            '💳 [PurchaseMembership] ✓ 域名切换成功，当前域名: ${KRDomain.kr_currentDomain}');
        print('💳 [PurchaseMembership] 🔄 使用新域名重试...');

        // 更新 HttpUtil 的 baseUrl
        HttpUtil.getInstance().updateBaseUrl();

        // 等待500ms让域名生效
        await Future.delayed(const Duration(milliseconds: 500));

        // 重试一次
        try {
          await kr_fetchPackages().timeout(
            const Duration(seconds: 8),
            onTimeout: () {
              print('💳 [PurchaseMembership] ❌ 使用新域名后仍然超时');
              KRLogUtil.kr_e('使用新域名后仍然超时', tag: 'PurchaseMembership');
            },
          );
          print('💳 [PurchaseMembership] ✓ 使用新域名重试成功，套餐数量: ${kr_plans.length}');
        } catch (retryError) {
          print('💳 [PurchaseMembership] ❌ 使用新域名重试仍然失败: $retryError');
          kr_errorMessage.value = '网络连接失败，请检查网络设置';
        }
      } else {
        print('💳 [PurchaseMembership] ❌ 域名切换失败，所有域名都不可用');
        kr_errorMessage.value = '无法连接服务器，请稍后重试';
      }
    } finally {
      kr_isLoading.value = false;
      print('💳 [PurchaseMembership] 加载状态设置为: false');
    }
  }

  /// 初始化用户信息
  Future<void> _iniUserInfo() async {
    _kr_balance = KRAppRunData().kr_balance;
  }

  /// 获取用户已订阅套餐
  Future<void> kr_getAlreadySubscribe() async {
    final either = await _kr_subscribeApi.kr_getAlreadySubscribe(includeExpired: 'all');
    either.fold(
      (error) => KRCommonUtil.kr_showToast(error.msg),
      (alreadySubscribe) {
        _kr_alreadySubscribe = alreadySubscribe;
        KRLogUtil.kr_i(
            '已获取所有订阅记录(含过期): ${_kr_alreadySubscribe.map((e) => "ID:${e.userSubscribeId}, SubID:${e.subscribeId}").toList()}',
            tag: 'PurchaseMembershipController');
      },
    );
  }

  /// 获取套餐列表
  Future<void> kr_fetchPackages() async {
    final either = await _kr_subscribeApi.kr_getPackageListList();
    either.fold(
      (error) => KRCommonUtil.kr_showToast(error.msg),
      (packageList) {
        kr_plans.value = packageList.kr_list;
        // 默认选择第一个套餐
        if (kr_plans.isNotEmpty) {
          kr_selectedPlanIndex.value = 0;
          kr_initializeSelection(kr_plans.first);
        }
      },
    );
  }

  /// 获取支付方式列表
  Future<void> kr_fetchPaymentMethods() async {
    final either = await _kr_subscribeApi.kr_getPaymentMethods();
    either.fold(
      (error) => KRCommonUtil.kr_showToast(error.msg),
      (paymentMethods) {
        kr_paymentMethods.value = paymentMethods;

        // 检查当前选择的套餐价格是否小于等于余额
        if (kr_plans.isNotEmpty) {
          final selectedPlan = kr_plans[kr_selectedPlanIndex.value];
          final selectedPrice = kr_getPlanPrice(selectedPlan,
              discountIndex: kr_selectedDiscountIndex.value);

          // 查找余额支付方式的索引
          final balanceMethodIndex = paymentMethods
              .indexWhere((method) => method.platform == 'balance');

          // 如果找到余额支付方式且余额足够，默认选择余额支付
          if (balanceMethodIndex != -1 && selectedPrice <= _kr_balance / 100) {
            kr_selectPaymentMethod(balanceMethodIndex);
          } else {
            // 查找第一个非余额支付方式
            final nonBalanceMethodIndex = paymentMethods
                .indexWhere((method) => method.platform != 'balance');
            if (nonBalanceMethodIndex != -1) {
              kr_selectPaymentMethod(nonBalanceMethodIndex);
            }
          }
        }
      },
    );
  }

  /// 获取公开的支付方式列表
  Future<void> _kr_fetchPublicPaymentMethods() async {
    final either = await _kr_subscribeApi.kr_getPublicPaymentMethods();
    either.fold(
      (error) {
        KRLogUtil.kr_e('获取公开支付方式失败: ${error.msg}',
            tag: 'PurchaseMembershipController');
      },
      (responseData) {
        KRLogUtil.kr_i('✅ 获取公开支付方式成功', tag: 'PurchaseMembershipController');

        try {
          // 解析支付方式数据
          final paymentMethodsData = KRPaymentMethods.fromJson(responseData);
          kr_paymentMethods.value = paymentMethodsData.list;

          KRLogUtil.kr_i('📊 支付方式数据已加载，共 ${kr_paymentMethods.length} 种',
              tag: 'PurchaseMembershipController');

          // 打印支付方式信息
          for (var method in kr_paymentMethods) {
            KRLogUtil.kr_i(
                '💳 支付方式: ${method.name} (ID: ${method.id}, Platform: ${method.platform})',
                tag: 'PurchaseMembershipController');
          }

          print('═══════════════════════════════════════');
          print('🔗 公开支付方式 API: /v1/public/payment/methods');
          print('📊 支付方式列表:');
          for (var i = 0; i < kr_paymentMethods.length; i++) {
            final method = kr_paymentMethods[i];
            print('  [$i] ${method.name} (platform: ${method.platform})');
          }
          print('═══════════════════════════════════════');

          // 如果有支付方式，默认选择第一个
          if (kr_paymentMethods.isNotEmpty) {
            kr_selectedPaymentMethodIndex.value = 0;
          }
        } catch (e) {
          KRLogUtil.kr_e('解析支付方式失败: $e', tag: 'PurchaseMembershipController');
        }
      },
    );
  }

  /// 获取支付方式显示标题
  String kr_getPaymentMethodTitle(KRPaymentMethod method) {
    if (method.platform == 'balance') {
      return '${method.name}(¥${(_kr_balance / 100).toStringAsFixed(2)})';
    }
    return method.name;
  }

  /// 选择套餐
  void kr_selectPlan(int planIndex, {int? discountIndex}) {
    if (planIndex >= 0 && planIndex < kr_plans.length) {
      kr_selectedPlanIndex.value = planIndex;

      // 确保折扣索引有效
      if (discountIndex != null) {
        final plan = kr_plans[planIndex];
        if (discountIndex >= 0 && discountIndex < plan.kr_discount.length) {
          kr_selectedDiscountIndex.value = discountIndex;
        } else {
          // 如果传入的折扣索引无效，但有折扣选项，则默认选择第一个
          if (plan.kr_discount.isNotEmpty) {
            kr_selectedDiscountIndex.value = 0;
          } else {
            kr_selectedDiscountIndex.value = -1;
          }
        }
      } else {
        // 如果没有传入折扣索引，但有折扣选项，则默认选择第一个
        final plan = kr_plans[planIndex];
        if (plan.kr_discount.isNotEmpty) {
          kr_selectedDiscountIndex.value = 0;
        } else {
          kr_selectedDiscountIndex.value = -1;
        }
      }

      // 重置支付方式选择
      kr_selectedPaymentMethodIndex.value = -1;

      // 重新判断应该选择的支付方式
      _kr_updatePaymentMethodSelection();

      // 更新UI状态
      update();
    }
  }

  /// 更新支付方式选择
  void _kr_updatePaymentMethodSelection() {
    if (kr_plans.isEmpty || kr_paymentMethods.isEmpty) return;

    final selectedPlan = kr_plans[kr_selectedPlanIndex.value];
    final selectedPrice = kr_getPlanPrice(selectedPlan,
        discountIndex: kr_selectedDiscountIndex.value);

    // 查找余额支付方式的索引
    final balanceMethodIndex =
        kr_paymentMethods.indexWhere((method) => method.platform == 'balance');
    // 如果找到余额支付方式且余额足够，选择余额支付
    if (balanceMethodIndex != -1 && selectedPrice <= _kr_balance / 100) {
      kr_selectPaymentMethod(balanceMethodIndex);
    } else {
      // 查找第一个非余额支付方式
      final nonBalanceMethodIndex = kr_paymentMethods
          .indexWhere((method) => method.platform != 'balance');
      if (nonBalanceMethodIndex != -1) {
        kr_selectPaymentMethod(nonBalanceMethodIndex);
      }
    }
  }

  /// 选择支付方式
  void kr_selectPaymentMethod(int index) {
    if (index >= 0 && index < kr_paymentMethods.length) {
      kr_selectedPaymentMethodIndex.value = index;
    }
  }

  /// 获取当前选中的数量
  int kr_getSelectedQuantity() {
    final selectedPlan = kr_plans[kr_selectedPlanIndex.value];
    if (kr_selectedDiscountIndex.value >= 0 &&
        kr_selectedDiscountIndex.value < selectedPlan.kr_discount.length) {
      return selectedPlan
          .kr_discount[kr_selectedDiscountIndex.value].kr_quantity;
    }
    return 1; // 默认数量为1
  }

  /// 开始订阅流程
  Future<void> kr_startSubscription() async {
    if (!kr_validateSubscriptionData()) return;
    print('开始订阅流程，选定支付');
    kr_errorMessage.value = '';

    // ✅ 1. iOS 核心拦截：检测本地是否有“挂起”的订单号
    if (Platform.isIOS) {
      final getPendingJwsData = await IAPPendingOrderService.getPendingJwsData();
      final getPendingOrderNo = await IAPPendingOrderService.getPendingOrderNo();

      if (getPendingJwsData != null && getPendingJwsData.isNotEmpty!) {
        print('🛑 [IAP] 拦截成功：发现未结单 $getPendingJwsData');

        await HIDialog.show(
          title: '检测到待激活订单',
          message: '您有一笔订单已支付成功，但尚未同步会员权益。请点击“立即激活”完成同步。',
          confirmText: '立即激活',
          cancelText: '取消',
          barrierDismissible: false,
          onConfirm:  () async{
            // 🚀 调用全局 Service 的重试逻辑
            try{
              await _kr_subscribeApi.kr_attachAppleIapTransaction(getPendingJwsData, getPendingOrderNo!);
              Get.offNamed(
                Routes.KR_ORDER_STATUS,
                arguments: {
                  'order': getPendingOrderNo,
                  'payment_type': 'apple_iap',
                  'checkout_type': 'ipa',
                },
              );
            }catch (e){
              KRCommonUtil.kr_showToast('激活失败，请重试');
            }

          },
        );
        return; // 🛑 关键：必须 return，阻止创建重复的新订单
      }
    }

    try {
      await kr_processPurchaseAndCheckout();
    } catch (e) {
      kr_errorMessage.value = '订阅失败: ${e.toString()}';
    }
  }

  /// 验证订阅数据
  bool kr_validateSubscriptionData() {
    if (kr_plans.isEmpty) {
      KRCommonUtil.kr_showToast('没有可用的套餐');
      return false;
    }

    // ⚠️ 支付方式接口暂未实现，暂时跳过支付方式验证
    // if (kr_selectedPaymentMethodIndex.value < 0 ||
    //     kr_selectedPaymentMethodIndex.value >= kr_paymentMethods.length) {
    //   KRCommonUtil.kr_showToast('请选择支付方式');
    //   return false;
    // }

    return true;
  }

  /// 处理购买和结账流程
  Future<void> kr_processPurchaseAndCheckout() async {
    final selectedPlan = kr_plans[kr_selectedPlanIndex.value];
    final isIOS = Platform.isIOS;

    // 1. 初始化为默认回退值
    int finalPaymentMethodId = 1;
    String finalPaymentPlatform = 'alipay';

    if (kr_paymentMethods.isNotEmpty) {
      // 检查是否有用户已选中且索引有效
      final bool isIndexValid = kr_selectedPaymentMethodIndex.value >= 0 &&
          kr_selectedPaymentMethodIndex.value < kr_paymentMethods.length;

      if (isIOS) {
        // 2. iOS 专属：查找 'stripe'
        final stripeMethod = kr_paymentMethods.firstWhere(
          (method) => method.platform == 'apple_iap',
        );

        if (stripeMethod != null) {
          // 找到了 Stripe，使用它
          finalPaymentMethodId = stripeMethod.id;
          finalPaymentPlatform = stripeMethod.platform;
        } else if (isIndexValid) {
          // 找不到 Stripe，但用户有选中，使用选中的方式
          finalPaymentMethodId =
              kr_paymentMethods[kr_selectedPaymentMethodIndex.value].id;
          finalPaymentPlatform =
              kr_paymentMethods[kr_selectedPaymentMethodIndex.value].platform;
        }
      } else {
        // 3. 非 iOS 环境：如果用户有选中，使用选中的方式
        if (isIndexValid) {
          finalPaymentMethodId =
              kr_paymentMethods[kr_selectedPaymentMethodIndex.value].id;
          finalPaymentPlatform =
              kr_paymentMethods[kr_selectedPaymentMethodIndex.value].platform;
        }
      }
    }

    final paymentMethodId = finalPaymentMethodId;
    final paymentPlatform = finalPaymentPlatform;
    // =========================================================================
    // 🔼 支付方式选择优化结束 🔼
    // =========================================================================
    final quantity = kr_getSelectedQuantity();

    // 判断是续订还是新购：查找匹配选中套餐 ID 的最后一项记录（最新的记录，可能已过期）
    final matchingSubscribes = _kr_alreadySubscribe
        .where((subscribe) => subscribe.subscribeId == selectedPlan.kr_id)
        .toList();
    
    final bool isRenewal = matchingSubscribes.isNotEmpty;
    final int subscribeId = isRenewal
        ? matchingSubscribes.last.userSubscribeId
        : 0;

    print('📊 [Purchase] 订阅判断: isRenewal=$isRenewal, userSubscribeId=$subscribeId');

    // 根据判断结果调用不同的接口
    final purchaseEither = isRenewal
        ? await _kr_subscribeApi.kr_renewal(
            subscribeId,
            quantity,
            paymentMethodId,
            '',
          )
        : await _kr_subscribeApi.kr_purchase(
            selectedPlan.kr_id,
            quantity,
            paymentMethodId,
            '',
          );

    purchaseEither.fold(
      (error) {
        print('❌ 请求失败:');
        print('  错误码: ${error.code}');
        print('  错误信息: ${error.msg}');
        print('═══════════════════════════════════════');
        KRCommonUtil.kr_showToast(error.msg);
      },
      (order) async {
        // 所有支付方式都需要调用 checkout 接口
        // final checkoutEither = await _kr_subscribeApi.kr_checkout(order);
        // checkoutEither.fold(
        //   (error) => KRCommonUtil.kr_showToast(error.msg),
        //   (uri) => Get.toNamed(
        //     Routes.KR_ORDER_STATUS,
        //     arguments: {
        //       'url': uri,
        //       'order': order,
        //       'payment_type': paymentPlatform,
        //     },
        //   ),
        // );
        print('✅ 请求成功:');
        print('  订单号: $order');
        print('═══════════════════════════════════════');

        // 调用 checkout 接口获取支付链接
        await _kr_handleCheckout(order, paymentPlatform);
      },
    );
  }

  /// iOS 固定价格映射表 (天数 : 价格)
  static const Map<int, double> _krIosPriceMap = {
    7: 3.29,
    30: 6.99,
    90: 14.99,
    365: 52.99,
  };

  /// 获取套餐价格
  /// discount: 0 表示无折扣（原价），其他值表示折扣百分比
  double kr_getPlanPrice(KRPackageListItem plan, {int? discountIndex}) {
    if (discountIndex != null &&
        discountIndex >= 0 &&
        discountIndex < plan.kr_discount.length) {
      // 计算折扣价格
      final discount = plan.kr_discount[discountIndex];
      // --- iOS 环境：使用本地硬编码价格 ---
      if (Platform.isIOS) {
        return _krIosPriceMap[discount.kr_quantity] ?? (plan.kr_unitPrice / 100);
      }
      // 如果 discount 是 0，则表示原价（100%）
      final discountRate =
          discount.kr_discount == 0 ? 100.0 : discount.kr_discount.toDouble();
      return (plan.kr_unitPrice / 100) *
          discount.kr_quantity *
          (discountRate / 100);
    }
    return plan.kr_unitPrice / 100;
  }

  /// 获取套餐每天价格
  double kr_getDayPlanPrice(KRPackageListItem plan, {int? discountIndex}) {
    if (discountIndex != null &&
        discountIndex >= 0 &&
        discountIndex < plan.kr_discount.length) {
      // 计算折扣价格
      final discount = plan.kr_discount[discountIndex];

      // --- iOS 显式逻辑 ---
      if (Platform.isIOS) {
        // 1. 先从映射表取总价
        // 2. 直接除以数量 kr_quantity
        return (_krIosPriceMap[discount.kr_quantity] ?? (plan.kr_unitPrice / 100)) / discount.kr_quantity;
      }

      return (plan.kr_unitPrice / 100) * (discount.kr_discount / 100);
    }
    return plan.kr_unitPrice / 100;
  }

  /// 获取时间字符串
  /// 根据 quantity 和 unit_time 转换成多语言描述
  /// Day: 7天 -> "一周"，30天 -> "一个月"，90天 -> "一个季度"，180天 -> "半年"，365天 -> "一年"
  /// Month: 3月 -> "一个季度"，6月 -> "半年"，12月 -> "一年"
  String kr_getTimeStr(KRPackageListItem plan, {int? discountIndex}) {
    final quantity = discountIndex != null &&
            discountIndex >= 0 &&
            discountIndex < plan.kr_discount.length
        ? plan.kr_discount[discountIndex].kr_quantity
        : 1;

    // 如果是 Day 单位，需要转换为对应的描述
    if (plan.kr_unitTime == 'Day') {
      return AppTranslations.kr_purchaseMembership.days(quantity);
      // switch (quantity) {
      //   case 7:
      //     return AppTranslations.kr_purchaseMembership.oneWeek;
      //   case 30:
      //     return AppTranslations.kr_purchaseMembership.oneMonth;
      //   case 90:
      //     return AppTranslations.kr_purchaseMembership.oneQuarter;
      //   case 180:
      //     return AppTranslations.kr_purchaseMembership.halfYear;
      //   case 365:
      //     return AppTranslations.kr_purchaseMembership.oneYear;
      //   default:
      //     return AppTranslations.kr_purchaseMembership.days(quantity);
      // }
    } else if (plan.kr_unitTime == 'Month') {
      // 月份也需要转换
      switch (quantity) {
        case 1:
          return AppTranslations.kr_purchaseMembership.oneMonth;
        case 3:
          return AppTranslations.kr_purchaseMembership.oneQuarter;
        case 6:
          return AppTranslations.kr_purchaseMembership.halfYear;
        case 12:
          return AppTranslations.kr_purchaseMembership.oneYear;
        default:
          return AppTranslations.kr_purchaseMembership.month(quantity);
      }
    } else if (plan.kr_unitTime == 'Year') {
      return AppTranslations.kr_purchaseMembership.year(quantity);
    }
    return '';
  }

  /// 获取折扣文本
  /// discount: 0 或 100 表示原价（无折扣），其他值表示折扣百分比
  String kr_getDiscountText(KRPackageListItem plan, int discountIndex) {
    if (Platform.isIOS) {
      if (discountIndex >= 0 && discountIndex < plan.kr_discount.length) {
        final discount = plan.kr_discount[discountIndex];
        if (discount.kr_quantity <= 7) return '';

        double baseDayPrice = 3.29 / 7;
        double currentDayPrice = (_krIosPriceMap[discount.kr_quantity] ?? 0.0) / discount.kr_quantity;

        if (currentDayPrice >= baseDayPrice - 0.001) return '';
        return '-${((1 - (currentDayPrice / baseDayPrice)) * 100).ceil()}%';
      }
      return '';
    }

    if (discountIndex >= 0 && discountIndex < plan.kr_discount.length) {
      final discount = plan.kr_discount[discountIndex];
      // 折扣值为 0 或 100 都表示原价，不需要显示折扣
      if (discount.kr_discount == 0 || discount.kr_discount == 100) {
        return '';
      }
      // 计算折扣百分比（例如：97% 显示为 -3%）
      final discountPercent = (100 - discount.kr_discount).ceil();
      return '${discountPercent}%';
    }
    return '';
  }

  /// 获取套餐总选项数
  int kr_getTotalOptionsCount(KRPackageListItem plan) {
    // 确保折扣列表不为空
    if (plan.kr_discount.isEmpty) {
      return 1; // 如果没有折扣选项，至少返回1个选项
    }
    return plan.kr_discount.length;
  }

  /// 初始化选择
  void kr_initializeSelection(KRPackageListItem plan) {
    if (plan.kr_discount.isNotEmpty) {
      // 默认选择第一个选项
      kr_selectedDiscountIndex.value = 0;
    } else {
      // 如果没有选项，设置为 -1
      kr_selectedDiscountIndex.value = -1;
    }
  }

  /// 获取当前选中套餐的描述
  String kr_getSelectedPlanDescription() {
    if (kr_selectedPlanIndex.value >= kr_plans.length) return '';
    final plan = kr_plans[kr_selectedPlanIndex.value];
    return plan.kr_description.kr_features
        .map((feature) => feature.kr_label)
        .join('、');
  }

  /// 获取当前选中套餐的特性标题列表
  List<String> kr_getSelectedPlanFeatureLabels() {
    if (kr_selectedPlanIndex.value >= kr_plans.length) return [];
    final plan = kr_plans[kr_selectedPlanIndex.value];
    return plan.kr_description.kr_features
        .map((feature) => feature.kr_label)
        .toList();
  }

  /// 获取当前选中套餐的详细信息
  List<KRFeature> kr_getSelectedPlanFeatures() {
    if (kr_selectedPlanIndex.value >= kr_plans.length) return [];
    final plan = kr_plans[kr_selectedPlanIndex.value];
    return plan.kr_description.kr_features;
  }

  /// 判断当前选中的套餐是否是续订
  bool kr_isRenewal() {
    if (kr_plans.isEmpty || _kr_alreadySubscribe.isEmpty) return false;
    final selectedPlan = kr_plans[kr_selectedPlanIndex.value];
    return _kr_alreadySubscribe
        .any((subscribe) => subscribe.subscribeId == selectedPlan.kr_id);
  }

  /// 获取当前选中套餐的订阅按钮文字
  String kr_getSubscribeButtonText() {
    if (kr_plans.isEmpty) return '';

    final selectedPlan = kr_plans[kr_selectedPlanIndex.value];
    final isRenewal = _kr_alreadySubscribe
        .any((subscribe) => subscribe.subscribeId == selectedPlan.kr_id);

    return isRenewal
        ? AppTranslations.kr_purchaseMembership.renewNow
        : AppTranslations.kr_purchaseMembership.startSubscription;
  }

  /// 切换描述展开状态
  void kr_toggleDescriptionExpanded() {
    kr_isDescriptionExpanded.value = !kr_isDescriptionExpanded.value;
  }

  /// 获取流量限制显示文本
  String kr_getTrafficLimitText(KRPackageListItem plan) {
    KRLogUtil.kr_i('原始流量值: ${plan.kr_traffic}', tag: 'TrafficLimit');
    if (plan.kr_traffic == 0) {
      return AppTranslations.kr_purchaseMembership.unlimitedTraffic;
    }
    // 将字节转换为GB
    final trafficInGB = plan.kr_traffic / (1024 * 1024 * 1024);
    KRLogUtil.kr_i('转换为GB后的值: $trafficInGB', tag: 'TrafficLimit');

    if (trafficInGB < 1) {
      return '${(trafficInGB * 1024).toStringAsFixed(0)}MB';
    } else if (trafficInGB < 1024) {
      return '${trafficInGB.toStringAsFixed(0)}GB';
    } else {
      return '${(trafficInGB / 1024).toStringAsFixed(1)}TB';
    }
  }

  /// 获取设备限制显示文本
  String kr_getDeviceLimitText(KRPackageListItem plan) {
    if (plan.kr_deviceLimit == 0) {
      return AppTranslations.kr_purchaseMembership.unlimitedDevices;
    }
    return AppTranslations.kr_purchaseMembership
        .devices(plan.kr_deviceLimit.toString());
  }

  /// 处理 checkout 并打开支付链接（参考 Tauri 项目）
  Future<void> _kr_handleCheckout(String orderNo, String paymentPlatform) async {
    print('');
    print('═══════════════════════════════════════');
    print('🔗 调用 Checkout 接口');
    print('📤 请求参数:');
    print('  orderNo: $orderNo');
    print('  returnUrl: ${AppConfig.getInstance().baseUrl}');
    print('');

    final checkoutEither = await _kr_subscribeApi.kr_checkout(orderNo);

    checkoutEither.fold(
      (error) {
        print('❌ Checkout 失败:');
        print('  错误码: ${error.code}');
        print('  错误信息: ${error.msg}');
        print('═══════════════════════════════════════');
        KRCommonUtil.kr_showToast(error.msg);
      },
      (checkoutResponse) async {
        print('✅ Checkout 成功:');
        print('  支付类型: ${checkoutResponse.type}');

        if (checkoutResponse.type == 'url') {
          // URL 类型：在浏览器中打开支付链接，同时跳转到订单状态页面
          if (checkoutResponse.checkoutUrl != null &&
              checkoutResponse.checkoutUrl!.isNotEmpty) {
            print('  支付链接: ${checkoutResponse.checkoutUrl}');
            print('🌐 正在用外部浏览器打开支付链接...');
            print('═══════════════════════════════════════');

            final url = Uri.parse(checkoutResponse.checkoutUrl!);
            if (await canLaunchUrl(url)) {
              // 在外部浏览器打开支付链接
              await launchUrl(
                url,
                mode: LaunchMode.externalApplication,
              );

              // 跳转到订单状态页面进行轮询检查
              Get.toNamed(
                Routes.KR_ORDER_STATUS,
                arguments: {
                  'url': checkoutResponse.checkoutUrl,
                  'order': orderNo,
                  'payment_type': paymentPlatform,
                  'checkout_type': 'url',
                },
              );
            } else {
              print('❌ 无法打开URL: ${checkoutResponse.checkoutUrl}');
              KRCommonUtil.kr_showToast('无法打开支付链接');
            }
          } else {
            print('⚠️ 支付链接为空');
            print('═══════════════════════════════════════');
            KRCommonUtil.kr_showToast('支付链接为空');
          }
        } else if (checkoutResponse.type == 'qr') {
          // QR 类型：显示二维码（跳转到订单状态页面）
          print('  二维码内容: ${checkoutResponse.checkoutUrl}');
          print('📱 显示二维码支付...');
          print('═══════════════════════════════════════');

          Get.toNamed(
            Routes.KR_ORDER_STATUS,
            arguments: {
              'url': checkoutResponse.checkoutUrl,
              'order': orderNo,
              'payment_type': paymentPlatform,
              'checkout_type': 'qr',
            },
          );
        } else if (checkoutResponse.type == 'stripe') {
          KRCommonUtil.kr_showToast('不支持 stripe方式');
         /* // Stripe 类型：显示 Stripe 支付表单
          print('  Stripe Method: ${checkoutResponse.stripe?.method}');
          print(
              '  Stripe Client Secret: ${checkoutResponse.stripe?.clientSecret}');
          print('💳 显示 Stripe 支付表单...');
          print('═══════════════════════════════════════');

          final clientSecret = checkoutResponse.stripe?.clientSecret;
          if (clientSecret == null || clientSecret.isEmpty) {
            KRCommonUtil.kr_showToast('缺少支付凭证，请稍后重试');
            return;
          }

          // 仅 iOS 使用 Apple Pay
          if (!Platform.isIOS) {
            KRCommonUtil.kr_showToast('Apple Pay 仅在 iOS 可用');
            return;
          }
          print(
              'Platform: ${Platform.operatingSystem} ${Platform.operatingSystemVersion}');
          print('Merchant identifier: ${Stripe.merchantIdentifier}');
          // 检查设备是否支持 Platform Pay（Apple Pay）
          final supported = await Stripe.instance.isPlatformPaySupported();
          if (!supported) {
            KRCommonUtil.kr_showToast('当前设备或 Wallet 不支持 Apple Pay，请确认已添加可用卡');
            return;
          }
          // 2. 创建确认支付的参数对象
          final params = PlatformPayConfirmParams.applePay(
            applePay: ApplePayParams(
              merchantCountryCode: 'US',
              currencyCode: 'USD',
              cartItems: [
                ApplePayCartSummaryItem.immediate(
                  label: 'Hi快VPN 服务',
                  amount: kr_getPlanPrice(kr_plans[kr_selectedPlanIndex.value],
                          discountIndex: kr_selectedDiscountIndex.value)
                      .toStringAsFixed(2),
                ),
              ],
            ),
          );

          // 🚀 3. 调用方法，直接启动 Apple Pay 原生界面
          await Stripe.instance.confirmPlatformPayPaymentIntent(
            clientSecret: clientSecret,
            confirmParams: params,
          );

          // C. 支付成功
          print('✅ Stripe 支付成功！');

          Get.toNamed(
            Routes.KR_ORDER_STATUS,
            arguments: {
              'order': orderNo,
              'payment_type': paymentPlatform,
              'checkout_type': 'stripe',
              'stripe': checkoutResponse.stripe,
            },
          );*/
        } else if (checkoutResponse.type == 'balance') {
          // Stripe 类型：显示 Stripe 支付表单
          print('  Stripe Method: ${checkoutResponse.stripe?.method}');
          print(
              '  Stripe Client Secret: ${checkoutResponse.stripe?.clientSecret}');
          print('💳 显示 Stripe 支付表单...');
          print('═══════════════════════════════════════');

          Get.toNamed(
            Routes.KR_ORDER_STATUS,
            arguments: {
              'order': orderNo,
              'payment_type': paymentPlatform,
              'uri': '',
              'checkout_type': 'balance',
            },
          );
        } else if (checkoutResponse.type == 'apple_iap') {
          if (!Platform.isIOS) {
            KRCommonUtil.kr_showToast('仅限在 iOS 设备上购买');
            return;
          }

          // 🔧 版本和地区检查逻辑
          try {
            final PackageInfo packageInfo = await PackageInfo.fromPlatform();
            final String currentVersion = packageInfo.version;
            final String curVersion = KRSiteConfigService().getCurVersion();

            print('💳 [IAP] 支付检查: App版本=$currentVersion, 服务端参考版本=$curVersion');

            if (curVersion.isNotEmpty) {
              // 如果代码中的version版本小于等于 curversion 时
              if (_kr_compareVersion(currentVersion, curVersion) <= 0) {
                // 判断 apple id 账号地区是否在香港(HK)、台湾(TW)
                // 使用 StoreKit 的地区代码（SKStorefront），它是根据当前登录的 App Store 账户决定的
                // 使用 StoreKit 2 的地区代码，它是根据当前登录的 App Store 账户决定的
                String storefrontCountryCode = '';
                try {
                  // StoreKit 2 API
                  final Storefront storefront = Storefront();
                  final String storefrontCountryCode = await storefront.countryCode();
                  print('💳 [IAP] Storefront 2 地区检查: countryCode=$storefrontCountryCode');
                } catch (e) {
                  print('💳 [IAP] 获取 Storefront 2 信息失败, 尝试使用系统地区作为后备: $e');
                  storefrontCountryCode = Get.deviceLocale?.countryCode ?? '';
                }

                // 定义 H5 支付白名单 (包含 2 位和 3 位国家代码)
                const h5WhiteList = [
                  'HKG', // 香港
                  'TWN', // 台湾
                  'MAC', // 澳门
                  'SGP', // 新加坡
                  'MYS', // 马来西亚
                  'THA', // 泰国
                  'VNM', // 越南
                  'PHL', // 菲律宾
                ];

                if (h5WhiteList.contains(storefrontCountryCode.toUpperCase())) {
                  final String token = KRAppRunData.getInstance().kr_token ?? '';
                  final String url = 'https://hifastvpn.com/login/$token';
                  print('💳 [IAP] 符合跳转条件 (Storefront: $storefrontCountryCode)，跳转至网页支付: $url');

                  final Uri uri = Uri.parse(url);
                  if (await canLaunchUrl(uri)) {
                    await launchUrl(uri, mode: LaunchMode.externalApplication);
                    return; // 终止后续苹果内购流程
                  }
                }
              }
            }
          } catch (e) {
            print('💳 [IAP] 版本或地区检查时发生异常: $e');
          }

          final KRIpaPayment iapParams = (checkoutResponse.ipa == null ||
                  (checkoutResponse.ipa?.productId.isEmpty ?? true))
              ? KRIpaPayment(
                  productId: 'com.hifastvpn.vip.day${kr_getSelectedQuantity()}')
              : checkoutResponse.ipa!;

          final iap = InAppPurchase.instance;
          final available = await iap.isAvailable();
          if (!available) {
            print('IAP 不可用');
            KRCommonUtil.kr_showToast('App Store 不可用');
            return;
          }

          final productIds = {iapParams.productId};
          final productDetailsResponse =
              await iap.queryProductDetails(productIds);
          if (productDetailsResponse.error != null) {
            final e = productDetailsResponse.error!;
            print('IAP 查询商品错误 code: ${e.code}');
            print('IAP 查询商品错误 message: ${e.message}');
            print('IAP 查询商品错误 iapParams.productId: ${iapParams.productId}');
            KRCommonUtil.kr_showToast('无法获取商品信息: ${e.message}');
            return;
          }
          if (productDetailsResponse.productDetails.isEmpty) {
            print('IAP 商品列表为空 productId: ${iapParams.productId}');
            KRCommonUtil.kr_showToast('未找到对应商品');
            return;
          }
          final product = productDetailsResponse.productDetails.first;

          final kr_userId = KRAppRunData.getInstance().kr_userId.value;
          final purchaseParam = PurchaseParam(
            productDetails: product,
            applicationUserName: 'uid_${kr_userId}|orderNo_${orderNo}',
          );

          // ----------------------------------------------------------------------
          // ProductDetails 已成功获取，并已构造 purchaseParam。
          // ----------------------------------------------------------------------

          try {
            await IAPPendingOrderService.setPendingOrderNo(orderNo);
            KRCommonUtil.kr_showLoading();
            final result =
                await iap.buyNonConsumable(purchaseParam: purchaseParam);
            if (!result) {
              KRCommonUtil.kr_hideLoading();
              KRCommonUtil.kr_showToast('购买请求失败，请重试');
            }
          } on PlatformException catch (e) {
            KRCommonUtil.kr_hideLoading();

            // --- 显式判断 iOS 取消异常 ---
            if (e.code == 'storekit2_purchase_cancelled') {
              print('ℹ️ [IAP] 确认：用户在 StoreKit2 弹窗中点击了取消');
              return; // 显式返回，不执行后续报错
            }

            // --- 显式判断 旧版 StoreKit 取消异常 ---
            if (e.code == 'storekit_error' && (e.message?.contains('cancelled') ?? false)) {
              print('ℹ️ [IAP] 确认：用户在旧版 StoreKit 中取消');
              return;
            }

            // 其他真正的平台异常
            KRCommonUtil.kr_showToast('购买服务暂不可用 (${e.code})');
          } catch (e) {
            // 处理非平台异常
            KRCommonUtil.kr_hideLoading();
            KRCommonUtil.kr_showToast('系统异常，请稍后重试');
          }
        } else {
          print('⚠️ 未知的支付类型: ${checkoutResponse.type}');
          print('═══════════════════════════════════════');
          // KRCommonUtil.kr_showToast('不支持的支付类型: ${checkoutResponse.type}');
        }
      },
    );
  }


  Future<void> kr_restorePurchases({bool isShowLoading = true}) async {
    print('重试');
    if(isShowLoading) {
      KRCommonUtil.kr_showLoading();
    }
    final iap = InAppPurchase.instance;
    await iap.restorePurchases();

    if(isShowLoading) {
      KRCommonUtil.kr_hideLoading();
    }
  }
  // 1. 新增恢复购买点击计数器
  int _restoreClickCount = 0;
  Future<void> clearPendingOrderNo() async {
    _restoreClickCount++;
    // 2. 检查点击次数是否超过3次
    if (_restoreClickCount > 3) {
      print('恢复购买点击次数超过3次，清理待处理订单...');
      await IAPPendingOrderService.clearPendingOrderNo();
      _restoreClickCount = 0; // 重置计数器
      KRCommonUtil.kr_hideLoading();
      KRCommonUtil.kr_showToast('已清理缓存，请重新尝试购买');
      return; // 终止后续操作
    }
  }

  /// 比较版本号
  /// 返回值：
  /// -1: v1 < v2
  ///  0: v1 == v2
  ///  1: v1 > v2
  int _kr_compareVersion(String v1, String v2) {
    if (v1.isEmpty || v2.isEmpty) return 0;
    try {
      List<String> list1 = v1.split('.');
      List<String> list2 = v2.split('.');
      int len = list1.length > list2.length ? list1.length : list2.length;
      for (int i = 0; i < len; i++) {
        int n1 = i < list1.length ? int.tryParse(list1[i]) ?? 0 : 0;
        int n2 = i < list2.length ? int.tryParse(list2[i]) ?? 0 : 0;
        if (n1 > n2) return 1;
        if (n1 < n2) return -1;
      }
    } catch (e) {
      print('版本比较失败: $e');
    }
    return 0;
  }
}
