import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/bean/talks.dart';
import 'package:electronic_assistant/data/repositories/agenda_repository.dart';
import 'package:electronic_assistant/data/repositories/config_repository.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:electronic_assistant/module/main/controller.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/event_bus.dart';
import 'package:electronic_assistant/widget/pull_to_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../data/api/response/example_info_response.dart';
import '../../data/bean/agenda.dart';
import '../../data/repositories/account_repository.dart';
import '../../utils/error_handler.dart';
import '../../utils/toast_util.dart';

class HomePageController extends BaseController {
  get isLogin => accountRepository.isLogin.value;

  get loginTxt => accountRepository.isLogin.value
      ? accountRepository.getUserSubName(accountRepository.phone)
      : StringName.homeGoLogin.tr;

  final refreshController = PullToRefreshController();

  BuildContext? todoTargetContext;

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

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

  @override
  void onReady() {
    super.onReady();
    refreshController.requestRefresh();

    eventBus.on(EventUserLogin, (arg) {
      requestHomeData();
    });

    eventBus.on(EventUserLogout, (arg) {
      talkRepository.setTalkList([]);
      agendaRepository.setAgendaList([]);
      requestHomeData();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    eventBus.off(EventUserLogin);
    eventBus.off(EventUserLogout);
  }

  void requestHomeData() async {
    try {
      if (accountRepository.isLogin.value) {
        await Future.wait([
          talkRepository.requestHomeTalkData(),
          agendaRepository.requestHomeAgendaData(),
        ]);
      } else {
        ExampleInfoResponse exampleInfo =
            await configRepository.getExampleInfo();
        talkRepository.setTalkList(
            exampleInfo.talkInfoList != null ? exampleInfo.talkInfoList! : []);
        agendaRepository.setAgendaList(
            exampleInfo.agendaList != null ? exampleInfo.agendaList! : []);
      }
    } catch (e) {
      refreshController.refreshCompleted();
      // Handle errors if necessary
    } finally {
      refreshController.refreshCompleted();
    }
  }

  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 goTalkRecordPage() {
    Get.find<MainController>().updateIndexByPageName(StringName.mainTabFile);
  }

  void showLoginDrawer() {
    Get.find<MainController>().openDrawer();
  }

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

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