import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:get/get.dart';
import '../../data/bean/character_group_info.dart';
import '../../data/bean/keyboard_info.dart';
import '../../data/repository/characters_repository.dart';
import '../../data/repository/keyboard_repository.dart';
import '../../utils/atmob_log.dart';

@injectable
class CharacterAddTabController extends BaseController
    with GetSingleTickerProviderStateMixin {
  final String tag = "CharacterAddTabController";

  final CharactersRepository charactersRepository;
  final KeyboardRepository keyboardRepository;

  // 键盘列表
  RxList<KeyboardInfo> get keyboardInfoList =>
      keyboardRepository.keyboardInfoList;

  late Rx<TabController> tabController;
  late PageController pageController;

  Rx<CharacterGroupInfo> currentCharacterGroupInfo = CharacterGroupInfo().obs;

  KeyboardInfo currentKeyboardInfo;

  RxList<CharacterGroupInfo> get characterGroupList =>
      charactersRepository.characterGroupList;

  @factoryMethod
  CharacterAddTabController(
    this.charactersRepository,
    this.keyboardRepository, {
    @factoryParam required this.currentKeyboardInfo,
  });

  RxInt currentTabBarIndex = 0.obs;

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

  void _dataLoad() async {
    pageController = PageController();
    tabController =
        TabController(
          length: characterGroupList.length,
          vsync: this,
          initialIndex: 0,
        ).obs;

    ever(charactersRepository.characterGroupList, (value) {
      AtmobLog.d(tag, "characterGroupList changed");
      if (value.isNotEmpty) {
        tabController.value.dispose();
        tabController.value = TabController(
          length: characterGroupList.length,
          vsync: this,
          initialIndex: 0,
        );
        currentCharacterGroupInfo.value = characterGroupList.first;
        AtmobLog.d(
          tag,
          "currentCharacterGroupInfo.value: ${characterGroupList.first.id}",
        );
      }
    });

    ever(keyboardRepository.keyboardInfoList, (value) {

      if (value.isNotEmpty) {
        currentKeyboardInfo = keyboardInfoList.first;
        print("currentKeyboardInfo.value: $currentKeyboardInfo");
      }
    });
  }

  void onTabChanged(int index) {
    if (index >= characterGroupList.length) {
      return;
    }

    pageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInToLinear,
    );
  }

  void onPageChanged(int index) {
    if (index >= characterGroupList.length) {
      return;
    }
    currentTabBarIndex.value = index;
    currentCharacterGroupInfo.value = characterGroupList[index];
    tabController.value.animateTo(
      index,
      duration: const Duration(milliseconds: 300),
    );
  }
}
