import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:get/get.dart';
import 'package:keyboard/data/bean/character_info.dart';
import 'package:keyboard/data/repository/account_repository.dart';
import 'package:keyboard/data/repository/characters_repository.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/module/main/main_page.dart';
import 'package:keyboard/utils/atmob_log.dart';

import '../../../data/api/response/keyboard_meme_explain_response.dart';
import '../../../data/api/response/user_info_response.dart';
import '../../../data/bean/keyboard_info.dart';
import '../../../resource/string.gen.dart';
import '../../../utils/age_zodiac_sign_util.dart';
import '../../../utils/error_handler.dart';
import '../../../utils/http_handler.dart';
import '../../../utils/toast_util.dart';

@injectable
class NewUserResultController extends BaseController {
  final tag = "NewUserResultController";

  final AccountRepository accountRepository;

  final KeyboardRepository keyboardRepository;

  final CharactersRepository charactersRepository;

  Rxn<UserInfoResponse> get _userInfo => accountRepository.userInfo;

  UserInfoResponse? get userInfo => _userInfo.value;

  Rx<KeyboardMemeExplainResponse> keyboardMemeExplain =
      KeyboardMemeExplainResponse().obs;

  final RxList<CharacterInfo> charactersList = <CharacterInfo>[].obs;

  final RxList<CharacterInfo> selectCharactersList = <CharacterInfo>[].obs;

  final Rx<KeyboardInfo> _newUserKeyboardInfo =
      KeyboardInfo().obs;

  KeyboardInfo get newUserKeyboardInfo => _newUserKeyboardInfo.value;

  NewUserResultController(
    this.accountRepository,
    this.keyboardRepository,
    this.charactersRepository,
  );

  @override
  void onInit() async {
    super.onInit();
    try {
      _newUserKeyboardInfo.value =
          Get.arguments["newUserKeyboardInfo"] as KeyboardInfo;
    } catch (e) {
      AtmobLog.e(tag, "获取新用户键盘信息失败: $e");
    }
    getMemeExplain();
    ever(_userInfo, (userInfo) {
      if (userInfo != null) {
        AtmobLog.d(tag, "获取用户信息成功");
        getMemeExplain();
      } else {
        AtmobLog.e(tag, "获取用户信息失败");
      }
    });

    getNewUserCharacterList();
  }

  clickBack() {
    Get.back();
  }

  void clickOpenNow() async {
    AtmobLog.d(tag, "点击立即使用");

    if (_newUserKeyboardInfo.value.id == null ||
        _newUserKeyboardInfo.value.id!.isEmpty) {
      return;
    }
    List<String> characterIds =
        selectCharactersList.map((e) => e.id).cast<String>().toList();
    keyboardRepository
        .keyboardCharacterStart(
          keyboardId: _newUserKeyboardInfo.value.id!,
          characterIds: characterIds,
        )
        .then((_) {
          print(
            '$tag keyboardCharacterUpdate success ${characterIds.toList()}',
          );
          AtmobLog.d(tag, "更新键盘人设成功");

          // 刷新键盘人设数据
          keyboardRepository.getKeyboardHomeInfo();

          MainPage.start();
        })
        .catchError((error) {
          if (error is ServerErrorException) {
            ToastUtil.show(error.message);
           }
      
        });
  }

  Future<void> getMemeExplain() async {
    try {
      if (!_isValid(userInfo?.birthday) ||
          !_isValid(_newUserKeyboardInfo.value.birthday)) {
        AtmobLog.e(tag, "生日信息不完整，无法获取星座");
        return;
      }
      final result = await keyboardRepository.getKeyboardMemeExplain(
        birthday: userInfo!.birthday!,
        targetBirthday: _newUserKeyboardInfo.value.birthday!,
      );
      keyboardMemeExplain.value = result;
      AtmobLog.d(tag, "获取星座梗语与解读成功");
    } catch (e) {
      AtmobLog.e(tag, "获取星座梗语与解读失败: $e");
    }
  }

  Future<void> getNewUserCharacterList() async {
    try {
      final result = await charactersRepository.getNewUserCharactersList();
      charactersList.value = result.characterInfo;
    } catch (e) {
      AtmobLog.e(tag, "获取新用户角色列表失败: $e");
    }
  }

  void onSelected(CharacterInfo characterInfo) {
    if (selectCharactersList.contains(characterInfo)) {
      selectCharactersList.remove(characterInfo);
    } else {
      selectCharactersList.add(characterInfo);
    }
  }

  bool _isValid(String? s) => s != null && s.trim().isNotEmpty;

  Zodiac? get zodiacLabelFromNewUserKeyboardInfo {
    final birthday = newUserKeyboardInfo.birthday;
    final gender = newUserKeyboardInfo.gender;
    if (birthday?.isEmpty != false || gender == null) return null;

    final zodiac = AgeZodiacSignUtil.getZodiacWithGenderLabel(
      birthday!,
      gender,
    );
    if (zodiac.name == '未知星座') return null;

    return zodiac;
  }

  Zodiac? get zodiacLabelFromUserInfo {
    final birthday = userInfo?.birthday;
    final gender = userInfo?.gender;

    if (birthday?.isEmpty != false || gender == null) return null;

    final zodiac = AgeZodiacSignUtil.getZodiacWithGenderLabel(
      birthday!,
      gender,
    );
    if (zodiac.name == '未知星座') return null;

    return zodiac;
  }
}
