account_apple_cubit.dart 4.06 KB
import 'dart:async';
import 'dart:io';

import 'package:appframe/config/locator.dart';
import 'package:appframe/config/routes.dart';
import 'package:appframe/data/repositories/user_auth_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

class AccountAppleState extends Equatable {
  final String appleId;
  final bool allowBind;

  const AccountAppleState({
    this.appleId = '',
    this.allowBind = false,
  });

  AccountAppleState copyWith({
    String? appleId,
    bool? allowBind,
  }) {
    return AccountAppleState(
      appleId: appleId ?? this.appleId,
      allowBind: allowBind ?? this.allowBind,
    );
  }

  @override
  List<Object?> get props => [
        appleId,
        allowBind,
      ];
}

class AccountAppleCubit extends Cubit<AccountAppleState> {
  late final UserAuthRepository _userAuthRepository;

  AccountAppleCubit(super.initialState) {
    _userAuthRepository = getIt.get<UserAuthRepository>();
  }

  ///
  /// 更换绑定Apple账号
  ///
  void change() async {
    // 仅iOS平台支持Apple登录
    if (!Platform.isIOS) {
      Fluttertoast.showToast(msg: '当前平台不支持Apple账号绑定', gravity: ToastGravity.TOP);
      return;
    }

    try {
      // 1. 获取Apple授权凭证
      AuthorizationCredentialAppleID credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      debugPrint('Apple更换绑定 - 用户唯一标识: ${credential.userIdentifier}');
      debugPrint('Apple更换绑定 - 授权码: ${credential.authorizationCode}');
      debugPrint('Apple更换绑定 - 身份令牌: ${credential.identityToken}');

      if (credential.userIdentifier == null) {
        Fluttertoast.showToast(msg: '授权失败', gravity: ToastGravity.TOP, backgroundColor: Colors.red);
        return;
      }

      // 2. 获取当前用户信息
      var sharedPreferences = getIt.get<SharedPreferences>();
      var currentUserCode = sharedPreferences.getString('auth_userCode') ?? '';
      if (currentUserCode.isEmpty) {
        Fluttertoast.showToast(msg: '用户信息获取失败,请重新登录', gravity: ToastGravity.TOP, backgroundColor: Colors.red);
        return;
      }

      // 3. 调用绑定接口
      var bindResult = await _userAuthRepository.newBinding(
        credential.userIdentifier!,
        currentUserCode,
        'apple',
      ) as Map<String, dynamic>?;

      if (bindResult != null && bindResult['code'] == 0) {
        Fluttertoast.showToast(msg: 'Apple账号更换绑定成功', gravity: ToastGravity.TOP);
        emit(state.copyWith(appleId: credential.userIdentifier!));
        router.pop({'appleId': credential.userIdentifier!});
      } else {
        var errorMsg = bindResult?['error'] ?? 'Apple账号更换绑定失败';
        Fluttertoast.showToast(msg: errorMsg, gravity: ToastGravity.TOP, backgroundColor: Colors.red);
      }
    } catch (e) {
      debugPrint('appleChange error: $e');
      // 用户取消授权时不提示错误
      if (e is SignInWithAppleAuthorizationException && e.code == AuthorizationErrorCode.canceled) {
        return;
      }
      Fluttertoast.showToast(msg: 'Apple账号更换绑定异常', gravity: ToastGravity.TOP, backgroundColor: Colors.red);
    }
  }

  Future<void> unbindApple() async {
    var sharedPreferences = getIt.get<SharedPreferences>();
    var userCode = sharedPreferences.getString('auth_userCode') ?? '';

    var result = await _userAuthRepository.unbind(userCode, null);
    if (result == null) {
      Fluttertoast.showToast(msg: '解绑失败');
      return;
    }
    if (result['code'] != 0) {
      Fluttertoast.showToast(msg: result['error']);
      return;
    }

    router.pop({'appleId': ''});
  }

  @override
  Future<void> close() async {
    await super.close();
  }
}