import 'dart:async';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/consts/event_report_id.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:electronic_assistant/module/talk/controller.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:electronic_assistant/utils/toast_util.dart';
import 'package:get/get.dart';

import '../../../data/bean/talk_original.dart';
import '../../../data/bean/talks.dart';
import '../../../data/repositories/account_repository.dart';

class OriginalController extends BaseController {
  final originalList = <TalkOriginal>[].obs;
  final String? talkId;

  StreamSubscription? _talkBeanListener;
  StreamSubscription? _talkStatusListener;
  StreamSubscription? _audioPlayingListener;

  OriginalController(this.talkId);

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

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

  void setPlayAutoSelection() {
    _audioPlayingListener = talkController.playingDuration.listen((duration) {
      if (duration == null) {
        return;
      }
      int time = duration.inMilliseconds;
      for (var item in originalList) {
        if (item.startMs == null || item.endMs == null) {
          continue;
        }
        if (item.startMs! <= time && item.endMs! >= time) {
          item.setSelected(true);
        } else {
          item.setSelected(false);
        }
      }
    });
  }

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

  void requestOriginal() {
    if (talkController.talkBean.value?.status.value ==
        TalkStatus.analysisSuccess) {
      eventReport(EventId.event_101300);
    } else if (talkController.talkBean.value?.status.value ==
        TalkStatus.analysisFail) {
      eventReport(EventId.event_101301);
    }
    if (originalList.isNotEmpty) {
      return;
    }
    talkRepository
        .talkOriginal(talkController.talkBean.value?.id)
        .then((value) {
      originalList.value = value;
    });
  }

  void talkTranslateClick(TalkOriginal item) {
    if (!accountRepository.isLogin.value) {
      ToastUtil.showToast(StringName.errorCodeNoLogin.tr);
      return;
    }
    if (item.getTranslateStatus() == TalkTranslate.translating ||
        item.getTranslateStatus() == TalkTranslate.translated) {
      return;
    }
    if (item.sentence == null || item.sentence!.isEmpty) {
      ToastUtil.showToast('翻译内容为空');
      return;
    }
    item.setTranslateStatus(TalkTranslate.translating);
    talkRepository.talkTranslate(item.sentence!).then((result) {
      item.setTranslateStatus(TalkTranslate.translated);
      item.setTranslatedSentence(result.translation);
    }).catchError((error) {
      item.setTranslateStatus(TalkTranslate.normal);
      ErrorHandler.toastError(error);
    });
  }

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