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/repositories/agenda_repository.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:electronic_assistant/module/chat/view.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

import '../../../data/api/request/agenda_update_bean.dart';

class AgendaDetailController extends BaseController {
  final Rxn<Agenda> detailBean = Rxn<Agenda>();
  final Rxn<TalkBean> talkBean = Rxn<TalkBean>();
  final etFieldController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    _getArguments();
  }

  void _getArguments() {
    if (Get.arguments is Agenda) {
      detailBean.value = Get.arguments as Agenda;
      requestTalkBeanData();
    }
  }

  void requestTalkBeanData() {
    String? talkId = detailBean.value?.talkId;
    if (talkId == null) {
      return;
    }
    talkRepository.talkInfo(talkId).then((data) {
      talkBean.value = data.talkInfo;
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onGoChatClick() {
    if (detailBean.value == null) {
      return;
    }
    if (talkBean.value == null) {
      ChatPage.startByTalkId(
          ChatFromType.fromAnalysisBtn, detailBean.value!.talkId,
          agenda: detailBean.value!);
    } else {
      ChatPage.startByTalk(ChatFromType.fromAnalysisBtn, talkBean.value!,
          agenda: detailBean.value!);
    }
  }

  void onTaskDoneClick() {
    if (detailBean.value == null) {
      return;
    }
    agendaRepository.agendaFinish(detailBean.value!.id, true).then((data) {
      agendaRepository.requestHomeAgendaData();
      Get.back();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onEditAgenda(String newContent) {
    if (detailBean.value == null) {
      return;
    }
    agendaRepository.agendaUpdate(detailBean.value!.talkId, [
      AgendaUpdateBean(detailBean.value!.id, detailBean.value!.name, newContent)
    ]).then((data) {
      detailBean.value!.content = newContent;
      etFieldController.clear();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  @override
  void onClose() {
    super.onClose();
    etFieldController.dispose();
  }
}
