import 'dart:async';
import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/bean/agenda.dart';
import 'package:electronic_assistant/dialog/alert_dialog.dart';
import 'package:electronic_assistant/module/talk/controller.dart';
import 'package:electronic_assistant/popup/talk_add_template_popup.dart';
import 'package:electronic_assistant/resource/colors.gen.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/mmkv_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../../data/bean/agenda_list_all_bean.dart';
import '../../../data/bean/talks.dart';
import '../../../data/bean/template_bean.dart';
import '../../../data/consts/constants.dart';
import '../../../data/consts/event_report_id.dart';
import '../../template/template_edit/view.dart';
import '../../template/template_list/view.dart';

class SummaryController extends BaseController {
  final String? talkId;

  StreamSubscription? _talkStatusListener;
  StreamSubscription? _talkBeanListener;

  SummaryController(this.talkId);

  TalkController get talkController => Get.find<TalkController>(tag: talkId);

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

  RxBool get _isEditModel => talkController.isEditModelRx;

  bool get isEditModel => _isEditModel.value;

  Rxn<TalkBean> get summaryBean => talkController.talkBean;

  List<TemplateBean>? get templateList => talkController.templateList.value;

  int? get templateSelectId => talkController.templateSelectId.value;

  GlobalKey addTemplateKey = GlobalKey();

  @override
  void onReady() {
    super.onReady();
    _talkBeanListener = talkController.talkBean.listen((bean) {
      _dealTalkUpdate();
    });
    _talkStatusListener =
        talkController.talkBean.value?.status.listen((status) {
      if (status == TalkStatus.analysisSuccess ||
          status == TalkStatus.analysisFail) {
        _dealTalkUpdate();
      }
    });
    _dealTalkUpdate();
  }

  Future<void> _checkShowGuide() async {
    debugPrint('checkShowGuide');
    if (addTemplateKey.currentContext == null) {
      return;
    }
    if (!KVUtil.getBool(GuideConstants.talkAddTemplateGuide, true)) {
      return;
    }
    KVUtil.putBool(GuideConstants.talkAddTemplateGuide, false);
    await Future.delayed(const Duration(milliseconds: 500));
    talkAddTemplatePopup(addTemplateKey.currentContext!);
  }

  void _dealTalkUpdate() {
    talkController.refreshTalkDetail().then((data) {
      if (data?.status.value == TalkStatus.analysisSuccess) {
        _checkShowGuide();
        eventReport(EventId.event_101100);
      } else if (data?.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);
  }

  void addTemplateClick() async {
    if (!await talkController.checkLogin()) {
      return;
    }
    //判断模板是否超出数量限制
    TalkBean? talkBean = talkController.talkBean.value;
    int? maxTemplateCount = talkController.maxTemplateCount;
    if (talkBean == null || maxTemplateCount == null) {
      return;
    }
    if ((talkController.templateList.value?.length ?? 0) >= maxTemplateCount) {
      _showMaxTemplateDialog();
      return;
    }
    dynamic isSuccess = await TemplateEditPage.addStart();
    if (isSuccess == true) {
      talkController.refreshTalkDetail();
    }
  }

  void _showMaxTemplateDialog() {
    EAAlertDialog.show(
        contentWidget: Container(
          padding: EdgeInsets.only(top: 20.w),
          child: Text(
            StringName.templateTooMuch.tr,
            style: TextStyle(
                fontSize: 15.sp,
                color: ColorName.primaryTextColor,
                fontWeight: FontWeight.bold),
          ),
        ),
        cancelText: StringName.cancel.tr,
        confirmText: StringName.templateToManage.tr,
        cancelOnTap: () {
          EAAlertDialog.dismiss();
        },
        confirmOnTap: () async {
          EAAlertDialog.dismiss();
          dynamic isSuccess = await TemplateListPage.start();
          if (isSuccess == true) {
            talkController.refreshTalkDetail();
          }
        });
  }

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

  void selectTemplate(TemplateBean template) {
    talkController.selectTemplate(template);
  }
}
