import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:get/get.dart';

import '../../../data/bean/custom_config_info.dart';
import '../../../data/repository/config_repository.dart';
import '../../../utils/atmob_log.dart';
import '../../../utils/toast_util.dart';

@injectable
class ChangeCharacterController extends BaseController {
  final String tag = "ChangeCharacterController";
  final ConfigRepository configRepository;

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

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

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

  ChangeCharacterController(this.configRepository);

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

    final List<CharactersList>? characters =
        Get.arguments["characters"] as List<CharactersList>?;
    if (characters != null) {
      characterSelectLabels.assignAll(characters);}
  }
  //  初始化数据
  void initData() {
    AtmobLog.d(tag, "initData");
    characterLabelsList.value = currentCharacterCustomConfig?.characters ?? [];
  }

  void selectCharacter(CharactersList name) {
    handleSelection(
      name: name,
      selectedList: characterSelectLabels,
      max: currentCharacterCustomConfig?.maxCharacterNum ?? 3,
      errorMessage:
          "最多选择${currentCharacterCustomConfig?.maxCharacterNum ?? 3}个关键词",
    );
  }

  ///标签选择处理
  void handleSelection({
    required dynamic name,
    required RxList<dynamic> selectedList,
    required int max,
    required String errorMessage,
  }) {
    if (selectedList.contains(name)) {
      selectedList.remove(name);
    } else if (selectedList.length < max) {
      selectedList.add(name);
    } else {
      ToastUtil.show(errorMessage);
    }
  }

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

  void clickSave() {
    if (characterSelectLabels.isEmpty) {
      ToastUtil.show(
        "至少选择${currentCharacterCustomConfig?.minCharacterNum ?? 1}个关键词",
      );
      return;
    }
    AtmobLog.d(
      tag,
      "clickSave characterSelectLabels: ${characterSelectLabels.toJson()}",
    );
    Get.back(result: characterSelectLabels);
  }
}
