import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.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/data/repository/keyboard_repository.dart';
import 'package:keyboard/dialog/login/login_dialog.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 '../../../data/consts/event_report.dart';
import '../../../dialog/custom_character/custom_character_another_add_dialog.dart';
import '../../../handler/event_handler.dart';
import '../../../utils/atmob_log.dart';
import '../../../utils/error_handler.dart';
import '../../../utils/http_handler.dart';
import '../character_custom_controller.dart';
import '../detail/character_custom_detail_page.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;

  final RxBool isLoading = false.obs;

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

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

    super.onReady();
    EventHandler.report(EventId.event_12008);

  }


  // 下拉刷新
  Future<void> refreshData() async {
    _currentPage.value = 1;
    isLoading.value = true;
    await getCurrentCharacterListInfo(isRefresh: true);
    Future.delayed(Duration(milliseconds: 500), () {
      isLoading.value = false;
    });
    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 {
    try {
      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!;
        }
      }
    } catch (error) {
      AtmobLog.e(tag, "getCurrentCharacterListInfo error: $error");
      if (error is ServerErrorException) {
        if (error.code == ErrorCode.noLoginError) {
          ErrorHandler.toastError(error);
          LoginDialog.show();
        } else {
          ToastUtil.show(error.message);
        }
      }
    }
  }

  void itemAddButtonClick(CharacterInfo characterInfo) async {
    AtmobLog.d(tag, 'characterInfo ${characterInfo.toJson()} ');
    EventHandler.report(EventId.event_12009);
    CustomCharacterAnotherAddDialog.show(customCharacterId: characterInfo.id!);

    // 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 itemEditClick(CharacterInfo characterInfo) async {
    var result = await CharacterCustomDetailPage.start(
      currentCharacterInfo: characterInfo,
    );
    if (result != null) {
      if (result is CharacterInfo) {
        // 更新列表
        int index = _characterList.indexWhere(
          (element) => element.id == result.id,
        );
        if (index != -1) {
          _characterList[index] = result;
        } else {
          _characterList.add(result);
        }
      }
    }
  }

  // 删除定制人设
  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();
  }

  void clickStartCustom(){
    EventHandler.report(EventId.event_12007);
    Get.back(result: StepType.hobbies);
  }
}
