import 'dart:ffi';

import 'package:domain/entity/user_me_entity.dart';
import 'package:domain/repository/profile_repository.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:plugin_basic/provider/user_config/user_config.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../../constants/app_constant.dart';
import '../global_provider_container.dart';

part 'user_config_service.g.dart';

/*
 * 用户的信息与状态的服务 - 全局单例
 */
@Riverpod(keepAlive: true)
class UserConfigService extends _$UserConfigService {
  late final ProfileRepository profileRepository;

  /// 静态方法获取当前单例对象
  static UserConfigService getInstance({WidgetRef? ref}) {
    if (ref != null) {
      return ref.watch(userConfigServiceProvider.notifier);
    } else {
      return globalContainer.read(userConfigServiceProvider.notifier);
    }
  }

  static UserConfig getState({WidgetRef? ref}) {
    if (ref != null) {
      return ref.watch(userConfigServiceProvider);
    } else {
      return globalContainer.read(userConfigServiceProvider);
    }
  }

  @override
  UserConfig build() {
    profileRepository = ref.read(profileRepositoryProvider);

    String? token = SPUtil.getString(AppConstant.storageToken);
    Log.d('UserService - 查询SP token：$token 并赋值');
    return UserConfig(token: token, hasLogin: Utils.isNotEmpty(token));
  }

  /// 静默请求用户的详情数据
  void refreshUserInfo() async {
    final result = await profileRepository.fetchUserInfo();
    if (result.isSuccess) {
      setUserInfo(result.data);
    } else {
      Log.e(result.errorMsg ?? "UnKnow Error");
    }
  }

  /// 设置用户信息
  void setUserInfo(UserMeEntity? user) {
    state = state.copyWith(user: user, userName: user?.name);
  }

  /// 设置全局的Token，同时更新 hasLogin 的值，赋值时机如下
  void setToken({String? token, String? userName}) {
    UserConfig configState = state.copyWith(token: token);

    if (Utils.isEmpty(token)) {
      configState.copyWith(hasLogin: false, userName: userName);
      SPUtil.remove(AppConstant.storageToken);
    } else {
      configState.copyWith(hasLogin: true, userName: userName);
      SPUtil.putString(AppConstant.storageToken, token!);
    }

    state = configState;

    Log.d('UserService =========> 设置Token为：$token');
  }

  /// 处理退出登录之后的数据清除
  void handleLogoutParams() {
    SPUtil.remove(AppConstant.storageToken);
    state = UserConfig(
      token: null,
      hasLogin: false,
      user: null,
      userName: null,
    );
  }
}
