import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:keyboard/data/repository/characters_repository.dart';
import 'package:keyboard/dialog/character_details_dialog.dart';
import 'package:keyboard/module/store/store_page.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard/utils/http_handler.dart';
import 'package:keyboard/utils/toast_util.dart';

import '../../../data/bean/character_group_info.dart';
import '../../../data/bean/character_info.dart';
import '../../../data/bean/keyboard_info.dart';
import '../../../utils/error_handler.dart';

@injectable
class CharacterTabGroupContentController extends BaseController {
  final KeyboardInfo currentKeyboardInfo;

  final CharacterGroupInfo currentCharacterGroupInfo;

  final CharactersRepository charactersRepository;

  @factoryMethod
  CharacterTabGroupContentController(
    this.charactersRepository, {
    @factoryParam required this.currentCharacterGroupInfo,
    @factoryParam required this.currentKeyboardInfo,
  });

  RxList<CharacterInfo> characterList = <CharacterInfo>[].obs;

  RxInt currentListCount = 0.obs;

  RxInt currentPage = 1.obs;
  late EasyRefreshController refreshController;

  @override
  void onInit() async {
    super.onInit();
    refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  onReady() {
    super.onReady();
    refreshData();
    AtmobLog.d("CharacterTabGroupContentController", "onReady");
  }

  // 下拉刷新
  Future<void> refreshData() async {
    currentPage.value = 1;

    await getCurrentCharacterListInfo(isRefresh: true);
    refreshController.finishRefresh();
    refreshController.resetFooter(); // 允许加载更多
  }

  // 上拉加载更多
  Future<void> loadMoreData() async {
    if (characterList.length >= currentListCount.value) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    currentPage.value++;
    await getCurrentCharacterListInfo(isRefresh: false);
    refreshController.finishLoad(IndicatorResult.success);
  }

  // 获取角色列表
  Future<void> getCurrentCharacterListInfo({bool isRefresh = false}) async {
    var response = await charactersRepository.getCharactersPage(
      groupId: currentCharacterGroupInfo.id.toString(),
      page: currentPage.value,
      keyboardId: currentKeyboardInfo.id.toString(),
    );
    if (isRefresh) {
      characterList.value = response.characterInfos;
    } else {
      characterList.addAll(response.characterInfos);
    }
    currentListCount.value = response.count;
  }

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

  void itemButtonClick(CharacterInfo characterInfo) {
    CharacterDetailsDialog.show(
      characterInfo: characterInfo,
      clickCallback: () {
        if (characterInfo.isAdd == false) {
          addCharacter(characterInfo);
        }
      },
    );
  }

  void addCharacter(CharacterInfo characterInfo) {
    charactersRepository
        .characterAdd(
          characterId: characterInfo.id.toString(),
          keyboardId: currentKeyboardInfo.id.toString(),
        )
        .then((characterAddResponse) {
          int index = characterList.indexWhere(
            (element) => element.id == characterAddResponse.characterInfo.id,
          );
          if (index != -1) {
            characterList[index] = characterAddResponse.characterInfo;
          }
          ToastUtil.show('添加成功~');
        })
        .catchError((error) {
          if (error is ServerErrorException && error.code == 1005) {
            ToastUtil.show('请开通会员解锁权益~');
            StorePage.start();
          }
          if (error is ServerErrorException && error.code == 1001) {
            ToastUtil.show('键盘人设已达上限，请取消其他人设再添加~');
          } else {
            ErrorHandler.toastError(error);
          }
        });
  }

  void unlockCharacter(CharacterInfo characterInfo) {
    charactersRepository
        .characterUnlock(
          characterId: characterInfo.id.toString(),
          keyboardId: currentKeyboardInfo.id.toString(),
        )
        .then((characterUnlockResponse) {
          int index = characterList.indexWhere(
            (element) => element.id == characterUnlockResponse.characterInfo.id,
          );
          if (index != -1) {
            characterList[index] = characterUnlockResponse.characterInfo;
          }
          ToastUtil.show('解锁成功~');
        })
        .catchError((error) {
          if (error is ServerErrorException && error.code == 1005) {
            ToastUtil.show('请开通会员解锁权益~');
            StorePage.start();
          } else {
            ErrorHandler.toastError(error);
          }
        });
  }
}
