purchase_controller.dart 16.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
import 'dart:async';

import 'package:doublefeel_flutter/app/modules/login/views/email_login_contact_us_bottom_sheet.dart';
import 'package:doublefeel_flutter/app/routes/app_pages.dart';
import 'package:doublefeel_flutter/core/config/app_environment_config.dart';
import 'package:doublefeel_flutter/core/constants/app_const.dart';
import 'package:doublefeel_flutter/core/constants/intent_keys.dart';
import 'package:doublefeel_flutter/core/network/api/pay_api.dart';
import 'package:doublefeel_flutter/core/network/api/vip_api.dart';
import 'package:doublefeel_flutter/core/platform/pigeon_api_facade.dart';
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:doublefeel_flutter/core/services/app_config_service.dart';
import 'package:doublefeel_flutter/core/services/thinking_data_service.dart';
import 'package:doublefeel_flutter/core/util/app_toast.dart';
import 'package:doublefeel_flutter/data/local/user_preferences_storage.dart';
import 'package:doublefeel_flutter/data/models/local/user_preferences.dart';
import 'package:doublefeel_flutter/data/models/pay/apple_pay_order_response.dart';
import 'package:doublefeel_flutter/data/models/pay/pay_models.dart';
import 'package:doublefeel_flutter/l10n/l10n_extensions.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../widgets/refund_explanation_bottom_sheet.dart';

class PurchasePlan {
  const PurchasePlan({
    required this.title,
    required this.subtitle,
    required this.price,
    required this.badge,
    this.product,
    this.appleProductId,
    this.actualPrice,
    this.appleProductInfo,
  });

  final String title;
  final String subtitle;
  final String price;
  final String badge;
  final PayProduct? product;
  final String? appleProductId;

  /// Real product price in cents, based on the Chinese price baseline.
  final int? actualPrice;

  final AppleProductInfo? appleProductInfo;
}

class PurchaseController extends GetxController {
  final PayApi _payApi = Get.find<PayApi>();
  final VipApi _vipApi = Get.find<VipApi>();
  final UserPreferencesStorage _userPreferences =
      Get.find<UserPreferencesStorage>();
  final AppPlatformHostApi _platformHostApi = AppPlatformHostApi();
  final AlipayHostApi _alipayHostApi = AlipayHostApi();

  final scrollController = ScrollController();
  final planScrollController = ScrollController();
  final plans = <PurchasePlan>[].obs;
  final selectedIndex = 0.obs;
  final isScrolled = false.obs;
  final isLoadingProducts = false.obs;
  final isUnlocking = false.obs;
  final isRestoring = false.obs;

  bool isFromOnboard = false;
  String channelType = '';
  final environmentConfig = Get.find<AppEnvironmentConfig>();

  @override
  void onInit() {
    super.onInit();
    final args = Get.arguments;
    if (args is Map) {
      isFromOnboard = args[IntentKeys.keyFrom] == 'onboarding';
      channelType = _nonEmpty(_stringArgument(args, IntentKeys.channelType)) ??
          _nonEmpty(_stringArgument(args, 'channelType')) ??
          (isFromOnboard ? '新手引导' : '');
    }
    scrollController.addListener(_handleScroll);
    unawaited(loadProductList());
  }

  @override
  void onReady() {
    super.onReady();
    _trackEnterVipCenter();
  }

  @override
  void onClose() {
    planScrollController.dispose();
    scrollController
      ..removeListener(_handleScroll)
      ..dispose();
    super.onClose();
  }

  void onBackPressed() {
    if (isFromOnboard) {
      if (Get.arguments?['is_membership_offer'] == true ||
          !AppConfigService.to.config.showYearVipDiscount) {
        Get.offAllNamed(AppRoutes.home, arguments: {'isFromOnboard': true});
      } else {
        Get.offNamed(
          Routes.MEMBERSHIP_OFFER,
          arguments: {'from': 'onboarding'},
        );
      }
    } else {
      if (Navigator.canPop(Get.context!)) {
        Get.back();
      } else {
        Get.offAllNamed(AppRoutes.home, arguments: {'isFromOnboard': true});
      }
    }
  }

  void _handleScroll() {
    final next = scrollController.hasClients && scrollController.offset > 250;
    if (next != isScrolled.value) {
      isScrolled.value = next;
    }
  }

  void selectPlan(int index) {
    if (index == selectedIndex.value) return;
    if (index < 0 || index >= plans.length) return;
    selectedIndex.value = index;
    if (!planScrollController.hasClients) return;
    planScrollController.animateTo(
      index * 232,
      duration: const Duration(milliseconds: 220),
      curve: Curves.easeOutCubic,
    );
  }

  /// Whether the current purchase flow uses HarmonyOS payment methods.
  bool get isOhos => _isOhos;

  /// The plan currently selected on the purchase page.
  PurchasePlan? get selectedPlan => _selectedPlan;

  Future<void> restorePurchase() async {
    if (isRestoring.value || isUnlocking.value) return;

    _trackClickVipCenter('恢复购买');
    isRestoring.value = true;
    try {
      final success = await _performRestore();
      if (success) {
        await _completeSuccessfulPurchase();
      }
    } finally {
      isRestoring.value = false;
    }
  }

  Future<void> unlock() async {
    if (isUnlocking.value || isRestoring.value) return;

    _trackClickVipCenter('立即购买');
    final plan = _selectedPlan;
    final productId = plan?.product?.id;
    if (_isOhos) {
      if (productId == null) {
        AppToast.show(l10n.purchaseProductInfoUnavailable);
        return;
      }
      await _unlockWithAlipay(productId);
      return;
    }

    final appleProductId = plan?.appleProductId;
    if (productId == null || appleProductId == null || appleProductId.isEmpty) {
      AppToast.show(l10n.purchaseProductInfoUnavailable);
      return;
    }

    isUnlocking.value = true;
    try {
      final orderResult = await _payApi.createOrderByApple(productId);
      if (orderResult case AppFailure<ApplePayOrderResponse>(:final error)) {
        AppToast.show(error.displayMessage);
        return;
      }
      if (orderResult is! AppSuccess<ApplePayOrderResponse>) return;

      final orderUuid = orderResult.data.orderInfo?.orderUuid?.trim();
      if (orderUuid == null || orderUuid.isEmpty) {
        AppToast.show(l10n.purchaseOrderInfoUnavailable);
        return;
      }

      final paymentResult = await _performApplePayment(
        productId: appleProductId,
        orderUuid: orderUuid,
      );
      await _handleApplePaymentResult(paymentResult);
    } finally {
      isUnlocking.value = false;
    }
  }

  /// Starts an App Pay transaction using the server-generated, RSA2-signed
  /// order string. The Alipay App ID is part of that order string, so neither
  /// the merchant private key nor any client-side signing is needed here.
  Future<void> _unlockWithAlipay(int productId) async {
    isUnlocking.value = true;
    try {
      final orderResult = await _payApi.createOrder(
        productId: productId,
        paymentChannel: PaymentChannel.alipay.value,
        productChannel: ProductChannel.huawei.value,
      );
      if (orderResult case AppFailure<CreatePayOrderResponse>(:final error)) {
        AppToast.show(error.displayMessage);
        return;
      }
      if (orderResult is! AppSuccess<CreatePayOrderResponse>) return;

      final prepayData = _nonEmpty(orderResult.data.prepayData);
      if (prepayData == null) {
        AppToast.show(l10n.purchaseOrderInfoUnavailable);
        return;
      }

      final result = await _alipayHostApi.launchAliPay(prepayData);
      if (result == AliPayResultCode.success) {
        _trackSuccessPayOrder();
        await _completeSuccessfulPurchase();
      } else if (result == AliPayResultCode.cancel) {
        AppToast.show(l10n.purchaseApplePaymentCancelled);
      } else if (result == AliPayResultCode.error) {
        AppToast.show(l10n.purchaseApplePaymentFailed);
      }
    } catch (_) {
      AppToast.show(l10n.purchaseApplePaymentFailed);
    } finally {
      isUnlocking.value = false;
    }
  }

  Future<void> loadProductList() async {
    isLoadingProducts.value = true;
    plans.clear();
    selectedIndex.value = 0;
    try {
      final result = await _payApi.getProductList();
      if (result is! AppSuccess<PayProductListResponse>) return;

      final products = (result.data.productList ?? const <PayProduct>[])
          .where((product) => _isOhos || _nonEmpty(product.appleId) != null)
          .toList();
      plans.assignAll(products.map(_buildPlan));
      final defaultProductIndex = products.indexWhere(
        (product) => product.content?.isDefaultProduct() ?? false,
      );
      selectedIndex.value = defaultProductIndex >= 0 ? defaultProductIndex : 0;
      isLoadingProducts.value = false;

      if (!_isOhos) {
        await Future.wait(
          products.indexed.map(
            (entry) => _loadAppleProductInfo(entry.$1, entry.$2),
          ),
        );
      }
    } finally {
      isLoadingProducts.value = false;
    }
  }

  Future<void> _loadAppleProductInfo(int index, PayProduct product) async {
    final appleProductId = _nonEmpty(product.appleId);
    if (appleProductId == null) return;

    final appleInfo = await _requestAppleProductInfo(
        productId: appleProductId, baseUnit: product.content?.baseUnit() ?? 1);
    if (appleInfo == null || index >= plans.length) return;
    if (plans[index].product?.id != product.id) return;

    plans[index] = _buildPlan(product, appleInfo);
  }

  Future<AppleProductInfo?> _requestAppleProductInfo({
    required String productId,
    required int baseUnit,
  }) async {
    try {
      return await _platformHostApi.requestAppleProductInfo(
        productId,
        baseUnit,
      );
    } catch (_) {
      return null;
    }
  }

  Future<AppleProductPaymentResult?> _performApplePayment({
    required String productId,
    required String orderUuid,
  }) async {
    try {
      return await _platformHostApi.performApplePayment(productId, orderUuid);
    } catch (_) {
      return null;
    }
  }

  Future<bool> _performRestore() async {
    try {
      return await _platformHostApi.performRestore();
    } catch (_) {
      return false;
    }
  }

  Future<void> _handleApplePaymentResult(
    AppleProductPaymentResult? result,
  ) async {
    if (result?.success == true) {
      _trackSuccessPayOrder();
      await _completeSuccessfulPurchase();
      return;
    }
    if (result?.success != false) return;

    AppToast.show(_applePaymentFailureMessage(result!));
  }

  Future<void> _completeSuccessfulPurchase() async {
    try {
      await _refreshVipInfo();
    } finally {
      if (isFromOnboard) {
        // onboarding 流程购买成功,清空栈进入首页
        Get.offAllNamed(AppRoutes.home, arguments: {'isFromOnboard': true});
      } else {
        Get.offNamed(Routes.PREMIUM_ACTIVATED);
      }
    }
  }

  Future<void> _refreshVipInfo() async {
    final result = await _vipApi.getVipInfo();
    if (result case AppSuccess(data: final vipInfo)) {
      await _userPreferences.updateVipInfo(
        UserPreferencesVipInfo.fromVipInfo(vipInfo),
      );
    }
  }

  String _applePaymentFailureMessage(AppleProductPaymentResult result) {
    final errorCode = result.errorCode;
    if (errorCode != null) {
      return _localizedApplePaymentErrorCode(errorCode);
    }

    final errorMessage = _nonEmpty(result.errorMessage);
    if (errorMessage == null) return l10n.purchaseApplePaymentFailed;
    return _localizedApplePaymentErrorMessage(errorMessage);
  }

  String _localizedApplePaymentErrorCode(int errorCode) {
    return switch (errorCode) {
      -1 => l10n.purchaseApplePaymentInvalidOrder,
      -2 => l10n.purchaseApplePaymentProductNotFound,
      -3 => l10n.purchaseApplePaymentCancelled,
      -4 => l10n.purchaseApplePaymentVerificationFailed,
      -5 => l10n.purchaseApplePaymentFailed,
      _ => l10n.purchaseApplePaymentFailed,
    };
  }

  String _localizedApplePaymentErrorMessage(String errorMessage) {
    if (errorMessage == 'missingUUID') {
      return l10n.purchaseApplePaymentInvalidOrder;
    }
    if (errorMessage == 'productNotFound') {
      return l10n.purchaseApplePaymentProductNotFound;
    }
    if (errorMessage == 'userCancelled') {
      return l10n.purchaseApplePaymentCancelled;
    }
    if (errorMessage == 'failedVerification') {
      return l10n.purchaseApplePaymentVerificationFailed;
    }
    if (errorMessage == 'unknown') {
      return l10n.purchaseApplePaymentFailed;
    }
    return errorMessage;
  }

  PurchasePlan? get _selectedPlan {
    final index = selectedIndex.value;
    if (index < 0 || index >= plans.length) return null;
    return plans[index];
  }

  PurchasePlan _buildPlan(PayProduct product, [AppleProductInfo? appleInfo]) {
    if (_isOhos) {
      // The product API may use 0 as the default value when no discount is
      // configured. Treat only a positive discount price as an active offer;
      // otherwise preserve the product's regular price.
      final discountPrice = product.discountPrice;
      final price = discountPrice != null && discountPrice > 0
          ? discountPrice
          : product.price;
      return PurchasePlan(
        title: _nonEmpty(product.name) ?? '',
        subtitle: _nonEmpty(product.content?.description) ?? '',
        price: price == null ? '' : _formatAlipayPrice(price),
        badge: _nonEmpty(product.content?.label) ?? '',
        product: product,
        actualPrice: price,
      );
    }

    var productName = appleInfo?.productName ?? _nonEmpty(product.name) ?? '';
    return PurchasePlan(
      title: productName,
      subtitle: _planSubtitle(product, appleInfo),
      price: appleInfo == null ? '' : _displayPrice(appleInfo),
      badge: _nonEmpty(product.content?.label) ?? '',
      product: product,
      appleProductId: product.appleId,
      actualPrice: appleInfo == null ? null : _actualPrice(appleInfo),
      appleProductInfo: appleInfo,
    );
  }

  String _planSubtitle(PayProduct product, AppleProductInfo? appleInfo) {
    if (product.content?.isYearProduct() != true) {
      return _nonEmpty(product.content?.description) ?? '';
    }

    final unitPrice = _nonEmpty(appleInfo?.unitPrice);
    return unitPrice == null ? '' : l10n.purchaseMonthlyUnitPrice(unitPrice);
  }

  String _displayPrice(AppleProductInfo appleInfo) {
    final price = appleInfo.price;
    if (price > 0) {
      final priceDescription = appleInfo.priceDescription.trim();
      if (priceDescription.isNotEmpty) {
        return priceDescription;
      }
    }
    return appleInfo.originPriceDescription;
  }

  int _actualPrice(AppleProductInfo appleInfo) {
    final price = appleInfo.price;
    if (price > 0) return price.round();
    return appleInfo.originPrice.round();
  }

  String _formatAlipayPrice(int amountInCents) {
    return ${(amountInCents / 100).toStringAsFixed(2)}';
  }

  bool get _isOhos => resolveAppPigeonPlatform() == AppPigeonPlatform.ohos;

  String? _nonEmpty(String? value) {
    final trimmed = value?.trim();
    if (trimmed == null || trimmed.isEmpty) return null;
    return trimmed;
  }

  String? _stringArgument(Map args, String key) {
    final value = args[key];
    return value is String ? value : null;
  }

  void openRefundExplanation() {
    _trackClickVipCenter('了解更多');
    showRefundExplanationBottomSheet();
  }

  void openContactUs() {
    _trackClickVipCenter('联系我们');
    feedbackCompat(pageName: 'Subscription page');
  }

  void openUserTerms() {
    String url = environmentConfig.region.value == AppRegion.china
        ? AppConst.userTerms
        : AppConst.userTermsGlobal;
    Get.toNamed(
      AppRoutes.webview,
      parameters: {'url': url},
    );
  }

  void openPrivacyPolicy() {
    String url = environmentConfig.region.value == AppRegion.china
        ? AppConst.privacyPolicy
        : AppConst.privacyPolicyGlobal;
    Get.toNamed(
      AppRoutes.webview,
      parameters: {'url': url},
    );
  }

  Map<String, dynamic> get _baseAnalyticsProperties =>
      {'channel_type': channelType};

  void _trackEnterVipCenter() {
    ta.track(
      'enter_doublefeel_vip_center',
      properties: _baseAnalyticsProperties,
    );
  }

  void _trackClickVipCenter(String clickContent) {
    ta.track(
      'click_doublefeel_vip_center',
      properties: {
        ..._baseAnalyticsProperties,
        'click_content': clickContent,
      },
    );
  }

  void _trackSuccessPayOrder() {
    final plan = _selectedPlan;
    final appleInfo = plan?.appleProductInfo;
    final actualPrice = appleInfo?.price ?? 0;
    ta.track(
      'success_doublefeel_pay_order',
      properties: {
        ..._baseAnalyticsProperties,
        'product_type': plan?.product?.appleId,
        'price': plan?.product?.price,
        'currency_code': appleInfo?.currencyCode ?? '',
        'actual_price':
            actualPrice > 0 ? actualPrice : (appleInfo?.originPrice ?? 0),
      },
    );
  }
}