import 'package:easy_refresh/easy_refresh.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:keyboard/data/repository/characters_repository.dart';
import 'package:keyboard/data/repository/keyboard_repository.dart';
import 'package:keyboard/utils/toast_util.dart';

import '../../../data/bean/character_info.dart';
import '../../../data/bean/keyboard_info.dart';
import '../../../data/consts/error_code.dart';
import '../../../dialog/character_details_dialog.dart';
import '../../../resource/string.gen.dart';
import '../../../utils/atmob_log.dart';
import '../../../utils/http_handler.dart';

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

  final RxInt _currentPage = 1.obs;

  final RxInt _currentListCount = 0.obs;

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

  List<CharacterInfo> get characterList => _characterList;

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

  final CharactersRepository charactersRepository;

  final KeyboardRepository keyboardRepository;

  late EasyRefreshController refreshController;

  CharacterCustomListController(
    this.charactersRepository,
    this.keyboardRepository,
  );

  @override
  void onInit() {
    super.onInit();
    refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
    // 等待页面渲染完成后再加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      refreshData();
    });
  }

  // 下拉刷新
  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.getCustomCharactersPage(
      pageSize: 10,
      page: _currentPage.value,
      keyboardId: _currentKeyboardInfo.value.id.toString(),
    );
    if (response.characterInfos != null) {
      if (isRefresh) {
        _characterList.value = response.characterInfos!;
      } else {
        _characterList.addAll(response.characterInfos!);
      }
      if (response.count != null) {
        _currentListCount.value = response.count!;
      }
    }
  }

  void itemButtonClick(CharacterInfo characterInfo) async {
    AtmobLog.d(tag, 'characterInfo ${characterInfo.toJson()} ');
    try {
      if (characterInfo.id != null) {
        await charactersRepository.addCustomCharacter(
          characterId: characterInfo.id!,
          keyboardId: _currentKeyboardInfo.value.id.toString(),
        );
      }

      ToastUtil.show("使用成功");
      Get.back(result: characterInfo);
    } catch (error) {
      if (error is ServerErrorException) {
        ToastUtil.show(error.message);
      }
    }
  }

  // 删除定制人设
  void itemDeleteClick(CharacterInfo characterInfo) async {
    AtmobLog.d(tag, 'characterInfo ${characterInfo.toJson()} ');
    if (characterInfo.isAdd == true) {
      ToastUtil.show("使用中，不可删除");
    }
    String? characterId = characterInfo.id;
    if (characterId != null) {
      try {
        await charactersRepository.deleteCustomCharacter(
          characterId: characterId,
        );
        _characterList.remove(characterInfo);
        ToastUtil.show("删除成功");
      } catch (error) {
        if (error is ServerErrorException) {
          ToastUtil.show(error.message);
        }
      }
    }
  }

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