import 'dart:async';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/bean/agenda.dart';
import 'package:electronic_assistant/data/bean/talks.dart';
import 'package:electronic_assistant/data/consts/event_report_id.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../../data/bean/agenda_list_all_bean.dart';
import '../controller.dart';

class SummaryController extends BaseController {
  final TalkController talkController = Get.find();

  final Rxn<TalkBean> summaryBean = Rxn();

  StreamSubscription? _talkStatusListener;

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

  RxBool get _isEditModel => talkController.isEditModelRx;

  bool get isEditModel => _isEditModel.value;

  @override
  void onReady() {
    super.onReady();
    _talkStatusListener =
        talkController.talkBean.value?.status.listen((status) {
      _dealTalkUpdate();
    });
    _dealTalkUpdate();
  }

  void _dealTalkUpdate() {
    refreshSummaryData();
  }

  void refreshSummaryData() {
    String? id = talkController.talkBean.value?.id;
    if (id == null) {
      return;
    }
    talkRepository.talkInfo(id).then((data) {
      summaryBean.value = data.talkInfo;
      if (data.talkInfo?.status.value == TalkStatus.analysisSuccess) {
        eventReport(EventId.event_101100);
      } else if (data.talkInfo?.status.value == TalkStatus.analysisFail) {
        eventReport(EventId.event_101101);
      }
    });
    talkController.refreshAgendaAllData();
  }

  void eventReport(String eventId, {Map<String, dynamic>? params}) {
    talkController.eventReport(eventId, params: params);
  }

  void removeTalkAgenda(List<Agenda>? list, Agenda agenda) {
    talkController.removeTalkAgenda(list, agenda);
  }

  void showAddAgendaDialog(BuildContext context) {
    talkController.showSingleAddAgendaDialog(context);
  }

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