import 'dart:async';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/bean/agenda.dart';
import 'package:electronic_assistant/data/repositories/agenda_repository.dart';
import 'package:electronic_assistant/module/chat/view.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:get/get.dart';
import '../../../data/bean/agenda_list_all_bean.dart';
import '../../../data/bean/talks.dart';
import '../controller.dart';

class TodoController extends BaseController {
  final TalkController _talkController = Get.find();

  StreamSubscription? _talkBeanListener;

  final agendaMineList = <Agenda>[].obs;

  final mineAgendaIsExpanded = false.obs;

  RxList<AgendaListAllBean> get agendaAllList => _talkController.agendaAllList;

  Rxn<TalkBean> get talkBean => _talkController.talkBean;

  @override
  void onReady() {
    super.onReady();
    _talkBeanListener = _talkController.talkBean.listen((bean) {
      _dealTalkUpdate(bean);
    });
    _dealTalkUpdate(_talkController.talkBean.value);
  }

  void _dealTalkUpdate(TalkBean? bean) {
    if (bean?.status.value == TalkStatus.analysisSuccess) {
      _talkController.refreshAgendaAllData();
      requestMineTodoData();
    }
  }

  void requestMineTodoData() {
    String? id = _talkController.talkBean.value?.id;
    if (id == null) {
      return;
    }
    agendaRepository.agendaListMine(id).then((data) {
      agendaMineList.value = data.list ?? [];
    });
  }

  @override
  void onClose() {
    super.onClose();
    _talkBeanListener?.cancel();
  }

  void agendaTodo(Agenda? agenda) {
    if (agenda == null) {
      return;
    }
    bool isSetTodo = !agenda.todo.value;
    agendaRepository.agendaTodo(agenda.id, isSetTodo).then((value) {
      agenda.todo.value = isSetTodo;
      requestMineTodoData();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onClickThinking(Agenda agenda) {
    TalkBean? bean = talkBean.value;
    if (bean != null) {
      ChatPage.startByTalk(bean, agenda: agenda);
    } else {
      ChatPage.start();
    }
  }
}
