import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/repositories/account_repository.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../data/api/response/example_info_response.dart';
import '../../data/bean/talks.dart';
import '../../data/repositories/config_repository.dart';
import '../../resource/string.gen.dart';
import '../../utils/toast_util.dart';

class FilesController extends BaseController {
  final refreshController = RefreshController(initialRefresh: false);

  int page = 1;

  int pageSize = 10;

  @override
  void onReady() {
    super.onReady();
    onRefreshData();
  }

  RxList<TalkBean> get talkList => talkRepository.talkList;

  void requestTalkData({int page = 1}) async {
    if (accountRepository.isLogin.value) {
      talkRepository.requestTalkPagePaginate(page, pageSize).then((response) {
        debugPrint("requestTalkData-response-$response");
        if (talkRepository.talkList.length >= response.count) {
          debugPrint("requestTalkData-没有更多数据了");
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        refreshController.refreshCompleted();
      }).catchError((error) {
        debugPrint("requestTalkData-catchError-$error");
        refreshController.loadFailed();
        refreshController.refreshFailed();
        ErrorHandler.toastError(error);
      });
    } else {
      ExampleInfoResponse exampleInfo = await configRepository.getExampleInfo();
      talkRepository.setTalkList(
          exampleInfo.talkInfoList != null ? exampleInfo.talkInfoList! : []);
      refreshController.refreshCompleted();
      refreshController.loadNoData();
    }
  }

  void onRefreshData() {
    page = 1;
    requestTalkData(page: page);
  }

  void onLoadMoreTalkData() {
    requestTalkData(page: ++page);
  }

  void requestName(String? newName, TalkBean bean) {
    talkRepository.talkRename(bean.id, newName).then((data) {
      bean.title.value = newName;
      ToastUtil.showToast(StringName.talkRenameSuccess.tr);
    }).catchError((error) {
      ErrorHandler.toastError(error, message: StringName.talkRenameFail.tr);
    });
  }

  void requestDelete(TalkBean item) {
    talkRepository.talkDelete(item.id).then((data) {
      onRefreshData();
      ToastUtil.showToast(StringName.talkDeleteSuccess.tr);
    }).catchError((error) {
      ErrorHandler.toastError(error, message: StringName.talkDeleteFail.tr);
    });
  }
}
