import 'dart:convert';

import 'package:injectable/injectable.dart';
import 'package:keyboard/data/api/response/character_custom_config_response.dart';

import '../../base/app_base_request.dart';
import '../../di/get_it.dart';
import '../../utils/async_util.dart';
import '../../utils/atmob_log.dart';
import '../../utils/http_handler.dart';
import '../../utils/intimacy_util.dart';
import '../api/atmob_api.dart';
import '../api/request/config_request.dart';
import '../api/response/config_response.dart';

import 'package:get/get.dart';

import '../bean/custom_config_info.dart';
import '../bean/default_avatar_info.dart';
import '../bean/intimacy_config_info.dart';

@lazySingleton
class ConfigRepository {
  final tag = "ConfigRepository";

  final AtmobApi atmobApi;

  final Rxn<CustomConfigInfo> _characterCustomConfig = Rxn<CustomConfigInfo>();

  // 里面包含人设头像
  Rxn<CustomConfigInfo> get characterCustomConfig => _characterCustomConfig;

  // 人物和键盘的头像
  final Rxn<DefaultAvatarInfo> defaultAvatarInfo = Rxn<DefaultAvatarInfo>();

  final Rxn<IntimacyConfigInfo> intimacyConfigInfo = Rxn<IntimacyConfigInfo>();

  ConfigRepository(this.atmobApi) {
    AtmobLog.d(tag, '$tag....init');
    refreshConfig();
    refreshCharacterCustomConfig();
  }

  // 更新配置的值
  void refreshConfig() {
    AsyncUtil.retry(
      () => requestConfigsData(),
      Duration(seconds: 4),
      maxRetry: 100,
    ).then((configsResponse) {
      final list = configsResponse.list;
      if (list == null || list.isEmpty) {
        return;
      }
      if (list.isNotEmpty) {
        for (var config in list) {
          if (config.confCode == 'intimacy') {
            intimacyConfigInfo.value = IntimacyConfigInfo.fromJson(
              config.value,
            );
            AtmobLog.d(tag, '获取亲密度配置: ${jsonEncode(list.map((e) => e.toJson()).toList())}');

            // IntimacyUtil.setConfig(intimacyConfigInfo.value);
          } else if (config.confCode == 'default_avatar') {
            defaultAvatarInfo.value = DefaultAvatarInfo.fromJson(config.value);
            AtmobLog.d(tag, '获取默认头像配置: ${defaultAvatarInfo.value?.toJson()}');
          }
        }
      }
    });
  }

  Future<void> refreshCharacterCustomConfig() async {
    try {
      final value = await getCharacterCustomConfig();
      _characterCustomConfig.value = value.customConfig;
    } catch (e) {
      AtmobLog.e(tag, "获取定制人设配置失败: $e");
    }
  }

  /// 获取配置信息
  Future<ConfigResponse> requestConfigsData() {
    return atmobApi
        .confs(ConfigRequest(confCodes: ['intimacy', 'default_avatar']))
        .then(HttpHandler.handle(true));
  }

  /// 获取定制人设配置
  Future<CharacterCustomConfigResponse> getCharacterCustomConfig() {
    return atmobApi
        .getCharacterCustomConfig(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }

  static ConfigRepository getInstance() => getIt.get<ConfigRepository>();
}
