import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/bean/character_info.dart';
import 'package:keyboard/data/bean/custom_config_info.dart';
import 'package:keyboard/data/repository/characters_repository.dart';
import 'package:get/get.dart';
import 'package:keyboard/data/repository/config_repository.dart';
import 'package:keyboard/module/character_custom/character_custom_controller.dart';
import 'package:keyboard/module/store/store_page.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/utils/atmob_log.dart';

import '../../../data/consts/error_code.dart';
import '../../../di/get_it.dart';
import '../../../dialog/keyboard_generating_dialog.dart';
import '../../../dialog/login/login_dialog.dart';
import '../../../resource/assets.gen.dart';
import '../../../router/app_pages.dart';
import '../../../utils/age_zodiac_sign_util.dart';
import '../../../utils/error_handler.dart';
import '../../../utils/http_handler.dart';
import '../../../utils/toast_util.dart';
import '../../change/birthday/change_birthday_page.dart';
import '../../change/character/change_character_page.dart';
import '../../change/gender/change_gender_page.dart';
import '../../change/hobbies/change_hobbies_page.dart';
import '../../change/nickname/change_nickname_page.dart';

// 定制人设详情页

enum CharacterCustomEditMode {
  add, // 新增
  edit, // 编辑
}

@injectable
class CharacterCustomDetailController extends BaseController {
  final String tag = 'CharacterCustomDetailController';

  final CharactersRepository charactersRepository;

  final ConfigRepository configRepository;

  CustomConfigInfo? get currentCharacterCustomConfig =>
      configRepository.characterCustomConfig.value;

  final RxList<Hobbies> _hobbiesSelectLabels = <Hobbies>[].obs;

  RxList<Hobbies> get hobbiesSelectLabels => _hobbiesSelectLabels;

  final RxList<CharactersList> _characterSelectLabels = <CharactersList>[].obs;

  RxList<CharactersList> get characterSelectLabels => _characterSelectLabels;

  final Rx<CharacterInfo> _currentCharacterInfo = CharacterInfo().obs;

  final RxString _currentNickname = "".obs;

  String get currentNickname => _currentNickname.value;

  final RxnInt _currentGender = RxnInt(null);

  final RxnString _currentBirthday = RxnString(null);

  String? get currentBirthday =>
      AgeZodiacSignUtil.formatBirthdayFromString(_currentBirthday.value);

  final RxString _avatarUrl = "".obs;

  String get avatarUrl => _avatarUrl.value;

  final List<String> _boyAvatars = [];

  final List<String> _girlAvatars = [];

  late final CharacterCustomEditMode mode;

  bool get isEditMode => mode == CharacterCustomEditMode.edit;

  bool get isAddMode => mode == CharacterCustomEditMode.add;

  final RxList<Hobbies> hobbiesLabelsList = <Hobbies>[].obs;

  final RxList<CharactersList> characterLabelsList = <CharactersList>[].obs;

  CharacterCustomDetailController(
    this.charactersRepository,
    this.configRepository,
  );

  @override
  void onInit() {
    super.onInit();

    initData();
    _getArgs();
  }

  void initData() {
    AtmobLog.d(tag, "initData");
    _boyAvatars.addAll(currentCharacterCustomConfig?.boyAvatars ?? []);
    _girlAvatars.addAll(currentCharacterCustomConfig?.girlAvatars ?? []);
    hobbiesLabelsList.value = currentCharacterCustomConfig?.hobbies ?? [];
    characterLabelsList.value = currentCharacterCustomConfig?.characters ?? [];
    if (_currentGender.value == 1) {
      _avatarUrl.value = _boyAvatars[0];
    } else {
      _avatarUrl.value = _girlAvatars[0];
    }
  }

  void _getArgs() {
    final arguments = Get.arguments as Map<String, dynamic>?;
    if (arguments?['currentCharacterInfo'] == null) {
      AtmobLog.i(tag, '没有传递 currentCharacterInfo 参数');
    } else {
      mode = CharacterCustomEditMode.edit;
      _currentCharacterInfo.value = arguments?['currentCharacterInfo'];

      List<String>? hobbies = _currentCharacterInfo.value.hobbies;
      print("hobbies: $hobbies");
      if (hobbies != null) {
        for (var hobby in hobbies) {
          final exists = hobbiesLabelsList.any((e) => e.name == hobby);
          if (!exists) {
            hobbiesLabelsList.add(Hobbies(name: hobby));
          }
          final selectedHobby = hobbiesLabelsList.firstWhere(
            (e) => e.name == hobby,
            orElse: () => Hobbies(name: hobby),
          );
          if (selectedHobby.name != null) {
            _hobbiesSelectLabels.add(selectedHobby);
          }
        }
      }

      List<String>? characters = _currentCharacterInfo.value.characters;
      if (characters != null) {
        for (var character in characters) {
          final exists = characterLabelsList.any((e) => e.name == character);
          if (!exists) {
            characterLabelsList.add(CharactersList(name: character));
          }
          final selectedCharacter = characterLabelsList.firstWhere(
            (e) => e.name == character,
            orElse: () => CharactersList(name: character),
          );
          if (selectedCharacter.name != null) {
            _characterSelectLabels.add(selectedCharacter);
          }
        }
      }
      _avatarUrl.value =
          _currentCharacterInfo.value.imageUrl ?? _avatarUrl.value;
      _currentNickname.value = _currentCharacterInfo.value.name ?? '';
      _currentGender.value = _currentCharacterInfo.value.gender;
      _currentBirthday.value = _currentCharacterInfo.value.birthday;
      return;
    }
    mode = CharacterCustomEditMode.add;
    if (arguments?['hobbiesSelectLabels'] == null) {
      AtmobLog.i(tag, '没有传递 hobbiesSelectLabels 参数');
    } else {
      _hobbiesSelectLabels.assignAll(arguments?['hobbiesSelectLabels'] ?? []);
      AtmobLog.i(tag, "hobbiesSelectLabels: $hobbiesSelectLabels");
    }

    if (arguments?['characterSelectLabels'] == null) {
      AtmobLog.i(tag, '没有传递 characterSelectLabels 参数');
    } else {
      _characterSelectLabels.assignAll(
        arguments?['characterSelectLabels'] ?? [],
      );
      AtmobLog.i(tag, "characterSelectLabels: $characterSelectLabels");
    }

    if (arguments?['characterCustomName'] == null) {
      AtmobLog.i(tag, ' 没有传递 characterCustomName 参数');
    } else {
      _currentNickname(arguments?['characterCustomName'] ?? '');
      AtmobLog.i(tag, "characterCustomName: $currentNickname");
    }
  }

  void nextAvatar() {
    AtmobLog.d(tag, "nextAvatar");

    if (_currentGender.value == 1) {
      int currentIndex = _boyAvatars.indexOf(_avatarUrl.value);
      _avatarUrl.value = _boyAvatars[(currentIndex + 1) % _boyAvatars.length];
    } else {
      int currentIndex = _girlAvatars.indexOf(_avatarUrl.value);
      _avatarUrl.value = _girlAvatars[(currentIndex + 1) % _girlAvatars.length];
    }
  }

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

  @override
  void onClose() {
    super.onClose();
  }

  void clickBack() {
    Get.back();
  }

  void clickNickname() async {
    AtmobLog.d(tag, 'clickNickname');
    final result = await ChangeNicknamePage.start(
      nickName: _currentNickname.value,
    );
    if (result != null) {
      _currentNickname.value = result;
    }
  }

  void clickUnlockButton() {
    AtmobLog.d(tag, "点击解锁按钮,生成专属人设");

    if (isEditMode) {
      updateCharacterCustom();
    } else {
      generateCharacterCustom();
    }
  }

  void clickGender() async {
    AtmobLog.d(tag, 'clickGender');
    final result = await ChangeGenderPage.start(gender: _currentGender.value);
    if (result != null) {
      _currentGender.value = result;
    }
    if (result == 1 && _boyAvatars.isNotEmpty) {
      _avatarUrl.value = _boyAvatars.first;
    } else if (_girlAvatars.isNotEmpty) {
      _avatarUrl.value = _girlAvatars.first;
    } else {
      _avatarUrl.value = "";
    }
  }

  String get genderText {
    if (_currentGender.value == 1) return '男';
    if (_currentGender.value == 2) return '女';
    return '请选择';
  }

  AssetGenImage? get genderImage {
    if (_currentGender.value == 1) {
      return Assets.images.iconCharacterCustomDetailMale;
    }
    if (_currentGender.value == 2) {
      return Assets.images.iconCharacterCustomDetailFemale;
    }
    return null;
  }

  void clickBirthday() async {
    AtmobLog.d(tag, 'clickBirthday');
    final result = await ChangeBirthdayPage.start(
      birthday: _currentBirthday.value,
    );
    if (result != null) {
      AtmobLog.d(tag, 'clickBirthday result: $result');
      _currentBirthday.value = result;
    }
  }

  void clickHobbies() async {
    AtmobLog.d(tag, 'clickHobbies');

    var result = await ChangeHobbiesPage.start(hobbies: _hobbiesSelectLabels);
    if (result is List<Hobbies>) {
      _hobbiesSelectLabels.assignAll(result);
    }
  }

  void clickCharacter() async {
    AtmobLog.d(tag, 'clickCharacter');

    var result = await ChangeCharacterPage.start(
      characters: _characterSelectLabels,
    );
    if (result is List<CharactersList>) {
      _characterSelectLabels.assignAll(result);
    }
  }

  // 生成定制人设
  Future<void> generateCharacterCustom() async {
    try {
      KeyboardGeneratingDialog.show();
      await charactersRepository.generateCharacterCustom(
        name: _currentNickname.value,
        gender: _currentGender.value,
        hobbies:
            _hobbiesSelectLabels
                .map((hobby) => hobby.name)
                .whereType<String>()
                .toList(),
        characters:
            _characterSelectLabels
                .map((character) => character.name)
                .whereType<String>()
                .toList(),
        birthday: _currentBirthday.value,
        imageUrl: _avatarUrl.value,
      );
      KeyboardGeneratingDialog.hide();
      Get.back();
      final characterCustomController = Get.find<CharacterCustomController>();
      characterCustomController.clearData();


      ToastUtil.show("生成成功");
    } catch (error) {
      if (error is ServerErrorException) {
        if (error.code == 1005) {
          StorePage.start();
          ToastUtil.show(error.message);
        } else if (error.code == ErrorCode.noLoginError) {
          LoginDialog.show();
        } else {
          ErrorHandler.toastError(error);
        }
      } else {
        ToastUtil.show(error.toString());
      }
      KeyboardGeneratingDialog.hide();
    }
  }

  //   更新专属人设
  Future<void> updateCharacterCustom() async {
    try {
      if (_currentCharacterInfo.value.id == null) {
        ToastUtil.show("当前人设为空");
        return;
      }
      await charactersRepository.characterCustomUpdate(
        id: _currentCharacterInfo.value.id!,
        name: _currentNickname.value,
        gender: 1,
        hobbies:
            _hobbiesSelectLabels
                .map((hobby) => hobby.name)
                .whereType<String>()
                .toList(),
        characters:
            _characterSelectLabels
                .map((character) => character.name)
                .whereType<String>()
                .toList(),
        birthday: _currentBirthday.value,
        imgUrl: _avatarUrl.value,
      );
      ToastUtil.show("更新成功");
      _currentCharacterInfo.value.name = _currentNickname.value;
      _currentCharacterInfo.value.birthday = _currentBirthday.value;
      _currentCharacterInfo.value.gender = _currentGender.value;
      _currentCharacterInfo.value.hobbies =
          _hobbiesSelectLabels.map((e) => e.name!).toList();
      _currentCharacterInfo.value.characters =
          _characterSelectLabels.map((e) => e.name!).toList();
      Get.back(result: _currentCharacterInfo.value);
    } catch (error) {
      if (error is ServerErrorException && error.code == 1005) {
        ToastUtil.show('请开通会员解锁权益~');
        StorePage.start();
      }
      if (error is ServerErrorException) {
        ErrorHandler.toastError(error);
      }
    }
  }
}
