import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.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/agenda.dart';
import '../../../data/consts/event_report_id.dart';
import '../../../data/repositories/account_repository.dart';
import '../../../data/repositories/agenda_repository.dart';
import '../../../data/repositories/config_repository.dart';
import '../../../handler/event_handler.dart';
import '../../../resource/string.gen.dart';
import '../../../router/app_pages.dart';
import '../../../utils/event_bus.dart';
import '../../../utils/toast_util.dart';
import '../../agenda/detail/view.dart';

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

  RxList<Agenda> get agendaList => agendaRepository.agendaList;

  @override
  void onReady() {
    super.onReady();
    eventBus.on(EventUserLogin, (arg) {
      requestHomeAgendaData();
    });
    eventBus.on(EventUserLogout, (arg) {
      agendaRepository.setAgendaList([]);
      requestHomeAgendaData();
    });
    requestHomeAgendaData();

    EventHandler.report(EventId.event_100101);
  }

  @override
  void onClose() {
    eventBus.off(EventUserLogin);
    eventBus.off(EventUserLogout);
  }

  void requestHomeAgendaData() async {
    try {
      if (accountRepository.isLogin.value) {
        await agendaRepository.requestHomeAgendaData();
      } else {
        ExampleInfoResponse exampleInfo =
            await configRepository.getExampleInfo();
        agendaRepository.setAgendaList(
            exampleInfo.agendaList != null ? exampleInfo.agendaList! : []);
      }
    } catch (e) {
      ErrorHandler.toastError(e);
    } finally {
      refreshController.refreshCompleted();
    }
  }

  onRefresh() {
    requestHomeAgendaData();
  }

  void onGoAgendaSeeAll() {
    if (!accountRepository.isLogin.value) {
      Get.toNamed(RoutePath.login);
      ToastUtil.showToast(StringName.errorCodeNoLogin.tr);
      return;
    }
    Get.toNamed(RoutePath.task);
  }

  void onAgendaItemClick(Agenda item) {
    AgendaDetailPage.start(item);
  }

  void agendaComplete(Agenda item) {
    agendaRepository.agendaFinish(item.id, true).then((data) {
      agendaRepository.requestHomeAgendaData();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }
}
