import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/bean/talks.dart';
import 'package:electronic_assistant/data/consts/event_report_id.dart';
import 'package:electronic_assistant/handler/event_handler.dart';
import 'package:electronic_assistant/module/record/constants.dart';
import 'package:electronic_assistant/module/record/record_handler.dart';
import 'package:electronic_assistant/module/talk/view.dart';
import 'package:electronic_assistant/utils/desktop_shortcut_utils.dart';
import 'package:electronic_assistant/utils/toast_util.dart';
import 'package:get/get.dart';
import '../../data/consts/error_code.dart';
import '../../dialog/alert_dialog.dart';
import '../../router/app_pages.dart';
import '../../utils/http_handler.dart';

class RecordController extends BaseController {
  Rx<RecordStatus> currentStatus = recordHandler.currentStatus;
  RxDouble currentDuration = recordHandler.currentDuration;

  @override
  void onInit() {
    super.onInit();
    recordHandler.init();
  }

  @override
  void onReady() async {
    super.onReady();
    EventHandler.report(EventId.event_100010,
        params: {EventId.id: EventId.id_001});
    if (!await RecordHandler.hasUnUploadRecord()) {
      _startOrContinueRecord();
    }
  }

  @override
  void onClose() {
    super.onClose();
    recordHandler.onClose();
  }

  void addShortcut() {
    DesktopShortcutUtils.requestAddDesktopShortcut();
  }

  void onBackClick() {
    Get.back();
  }

  void onActionClick() {
    RecordStatus nextStatus = currentStatus.value.nextStatus;
    if (nextStatus == RecordStatus.recording) {
      _startOrContinueRecord();
    } else {
      recordHandler.stopRecord();
    }
  }

  void onCancelClick() {
    if (currentStatus.value == RecordStatus.pending) {
      return;
    }
    EAAlertDialog.show(
      title: "是否删除当前录音？",
      confirmText: "删除",
      cancelText: "取消",
      confirmOnTap: () async {
        await recordHandler.deleteCurrentRecord();
        EAAlertDialog.dismiss();
        Get.back();
      },
      cancelOnTap: () {
        EAAlertDialog.dismiss();
      },
    );
  }

  void onSaveClick() {
    if (currentStatus.value == RecordStatus.pending) {
      return;
    }
    EventHandler.report(EventId.event_100011);
    _saveCurrentRecord();
  }

  Future<void> _startOrContinueRecord() async {
    recordHandler.startOrContinueRecord();
  }

  Future<void> _saveCurrentRecord() async {
    try {
      TalkBean talkInfo = await recordHandler.saveCurrentRecord();
      _dealSuccessNextStep(talkInfo);
    } catch (error) {
      if (error is ServerErrorException) {
        if (error.code == ErrorCode.errorCodeNoLogin) {
          ToastUtil.showToast("录音已保存，请登录");
          Get.toNamed(RoutePath.login)?.then((loginSuccess) {
            loginSuccess != null && loginSuccess ? _saveCurrentRecord() : null;
          });
        } else {
          ToastUtil.showToast("${error.message}");
        }
      } else {
        ToastUtil.showToast("录音已保存，请检查网络并重试");
      }
    }
  }

  void _dealSuccessNextStep(TalkBean talkInfo) {
    DesktopShortcutUtils.isShowTipsDialog(() {
      _routerToTalkPage(talkInfo);
    });
  }

  //跳转至谈话详情界面
  void _routerToTalkPage(TalkBean talkInfo) {
    Get.back();
    TalkPage.start(talkInfo, eventTag: EventId.id_001);
  }
}
