// ignore_for_file: non_constant_identifier_names
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/notification.m.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/services/notification/local_notification_service.dart';
import 'package:flyinsono/notifications/handlers/schedule/Invitee_reject_apply_handler.dart';
import 'package:flyinsono/notifications/handlers/schedule/applay_handler.dart';
import 'package:flyinsono/notifications/handlers/schedule/approval_apply_handler.dart';
import 'package:flyinsono/notifications/handlers/schedule/invitee_approve_apply_handler.dart';
import 'package:flyinsono/notifications/handlers/schedule/invitee_approve_handler.dart';
import 'package:flyinsono/notifications/handlers/schedule/reject_apply_handler.dart';
import 'package:flyinsono/notifications/handlers/schedule/remind_handler.dart';
import 'package:flyinsono/pages/schedule/calendar/utils/calendar_utils.dart';
import 'package:get/get.dart';

/// 移动端全局消息通知
class MobileScheduleNotificationService extends GetxService {
  MobileScheduleNotificationService();
  late LocalNotificationService localNotificationService;

  void handleReceiveNotification(SystemNotification notification) {
    Get.find<LocalNotificationService>().showNotification(
      notification.title,
      notification.info,
      notification.detailTitle,
      notification.detailInfos,
      notification.payload,
    );
  }

  /// 消息类型表
  /// RejectApplayNotificationHandler 📅| 6 | 拒绝会诊申请的通知
  /// ConsultationRemindNotificationHandler 📅| 9 | 会诊开始前提醒的通知
  /// ApplyConsultationHandler 📅| 22 | 会诊申请通知
  /// ApprovalApplyConsultationHandler 📅| 23 | 批准申请会诊通知
  /// InviteeConsultationNotificationHandler 📅| 24 | 会诊受邀请人通知
  /// InviteeApproveApplyConsultationNotificationHandler 📅| 25 | 会诊受邀请参与人同意通知
  /// InviteeRejectNotificationHandler 📅| 26 | 会诊受邀请参与人拒绝通知

  late RejectApplayNotificationHandler RANHandler;
  late ConsultationRemindNotificationHandler CRNHandler;
  late ApplyConsultationHandler ACHandler;
  late ApprovalApplyConsultationHandler AAHandler;
  late InviteeConsultationNotificationHandler ICNHandler;
  late InviteeApproveApplyConsultationNotificationHandler IAAHandler;
  late InviteeRejectNotificationHandler IRNHandler;

  @override
  void onInit() {
    super.onInit();
    localNotificationService = Get.find<LocalNotificationService>();
    localNotificationService.onNotificationClick
        .addListener(_onNotificationClick);
  }

  @override
  void onClose() {
    super.onClose();
    localNotificationService.onNotificationClick
        .addListener(_onNotificationClick);
  }

  /// 点击通知事件回调
  void _onNotificationClick(_, Payload payload) {
    if (payload.type == PayloadType.consultation) {
      _openConsultationDetail(payload.message);
    }
  }

  /// 点击通知进入详情页
  void _openConsultationDetail(String consultationCode) async {
    try {
      await router.to(MobileRouteNames.RealTimeRemedical.ConsultationDetail,
          parameters: {
            'consultationCode': consultationCode,
          });
    } catch (e) {
      logger.e("openEditInit exception:", e);
      printError(info: e.toString());
    }
  }

  /// 更新通知订阅
  void updateNotificationService() {
    RANHandler = Get.find<RejectApplayNotificationHandler>();
    RANHandler.subscribe(_onRejectApplay);
    CRNHandler = Get.find<ConsultationRemindNotificationHandler>();
    CRNHandler.subscribe(_onConsultationRemind);
    ACHandler = Get.find<ApplyConsultationHandler>();
    ACHandler.subscribe(_onApplyConsultation);
    AAHandler = Get.find<ApprovalApplyConsultationHandler>();
    AAHandler.subscribe(_onApprovalApplyConsultation);
    ICNHandler = Get.find<InviteeConsultationNotificationHandler>();
    ICNHandler.subscribe(_onInviteeConsultation);
    IAAHandler = Get.find<InviteeApproveApplyConsultationNotificationHandler>();
    IAAHandler.subscribe(_onInviteeApproveApplyConsultation);
    IRNHandler = Get.find<InviteeRejectNotificationHandler>();
    IRNHandler.subscribe(_onInviteeReject);
  }

  /// 会诊开始前提醒
  void _onConsultationRemind(ConsultationRemindNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.consultationWillStartIn
          .translate([CalendarUtils.minutesToDuration(message.countdownTime)]),
      info: i18nBook.notification.consultationWillStartIn
          .translate([CalendarUtils.minutesToDuration(message.countdownTime)]),
      detailInfos: [
        if (message.patientName != null)
          "${i18nBook.common.fullName.t} : ${message.patientName!}",
        if (message.consultationTime != null &&
            message.consultationTimeEnd != null)
          "${i18nBook.notification.consultationTime.t} : ${CalendarUtils.formatDateRange(message.consultationTime!.toLocal(), message.consultationTimeEnd!.toLocal())}",
        if (message.expertName != null)
          "${i18nBook.notification.expertName.t} : ${message.expertName!}",
      ],
      payload: Payload(
          type: PayloadType.consultation, message: message.consultationCode!),
    );
    handleReceiveNotification(notification);
  }

  /// 会诊申请通知
  void _onApplyConsultation(ApplyConsultationNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.receiveConsultationApply
          .translate(["${message.operatorName ?? ""}"]),
      info: i18nBook.notification.receiveConsultationApply4Mobile
          .translate(["${message.operatorName ?? ""}"]),
      detailInfos: [
        if (message.patientName != null)
          "${i18nBook.common.fullName.t} : ${message.patientName!}",
        if (message.consultationTime != null)
          "${i18nBook.notification.consultationTime.t} : ${CalendarUtils.formatDate(message.consultationTime!.toLocal())}",
        if (message.applyOrganizationName != null)
          "${i18nBook.notification.applyHospital.t} : ${message.applyOrganizationName!}",
      ],
      payload: Payload(
          type: PayloadType.consultation, message: message.consultationCode!),
    );
    handleReceiveNotification(notification);
  }

  /// 拒绝会诊申请通知
  void _onRejectApplay(RejectApplyConsultationNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.someoneRejectYourConsultation
          .translate(["${message.operatorName ?? ""}"]),
      info: i18nBook.notification.someoneRejectYourConsultation
          .translate(["${message.operatorName ?? ""}"]),
      detailInfos: [
        if (message.rejectReason != null)
          "${i18nBook.notification.rejectReason.t} : ${message.rejectReason!}",
      ],
      payload: Payload(
          type: PayloadType.consultation,
          message: message.consultationCode ?? ""),
    );
    handleReceiveNotification(notification);
  }

  /// 同意会诊申请通知
  void _onApprovalApplyConsultation(
      ApprovalApplyConsultationNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.someoneAcceptYourConsultation
          .translate(["${message.operatorName ?? ""}"]),
      info: i18nBook.notification.someoneAcceptYourConsultation
          .translate(["${message.operatorName ?? ""}"]),
      detailInfos: [
        if (message.patientName != null)
          "${i18nBook.common.fullName.t} : ${message.patientName!}",
        if (message.consultationTime != null &&
            message.consultationTimeEnd != null)
          "${i18nBook.notification.consultationTime.t} : ${CalendarUtils.formatDateRange(message.consultationTime!.toLocal(), message.consultationTimeEnd!.toLocal())}",
        if (message.expertName != null)
          "${i18nBook.notification.expertName.t} : ${message.expertName!}",
      ],
      payload: Payload(
          type: PayloadType.consultation,
          message: message.consultationCode ?? ""),
    );
    handleReceiveNotification(notification);
  }

  /// 会诊邀约通知
  void _onInviteeConsultation(InviteeConsultationNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.receiveConsultationInvitation
          .translate(["${message.operatorName ?? ""}"]),
      info: i18nBook.notification.receiveConsultationInvitation4Mobile
          .translate(["${message.operatorName ?? ""}"]),
      detailInfos: [
        if (message.patientName != null)
          "${i18nBook.common.fullName.t} : ${message.patientName!}",
        if (message.consultationTime != null &&
            message.consultationTimeEnd != null)
          "${i18nBook.notification.consultationTime.t} : ${CalendarUtils.formatDateRange(message.consultationTime!.toLocal(), message.consultationTimeEnd!.toLocal())}",
      ],
      payload: Payload(
          type: PayloadType.consultation, message: message.consultationCode!),
    );
    handleReceiveNotification(notification);
  }

  /// 同意会诊邀约通知
  void _onInviteeApproveApplyConsultation(
      InviteeApproveApplyConsultationNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.someoneAcceptYourInvitation
          .translate(["${message.operatorName ?? ""}"]),
      info: i18nBook.notification.someoneAcceptYourInvitation
          .translate(["${message.operatorName ?? ""}"]),
      detailInfos: [
        if (message.patientName != null)
          "${i18nBook.common.fullName.t} : ${message.patientName!}",
        if (message.consultationTime != null &&
            message.consultationTimeEnd != null)
          "${i18nBook.notification.consultationTime.t} : ${CalendarUtils.formatDateRange(message.consultationTime!.toLocal(), message.consultationTimeEnd!.toLocal())}",
      ],
      payload: Payload(
          type: PayloadType.consultation,
          message: message.consultationCode ?? ""),
    );
    handleReceiveNotification(notification);
  }

  /// 拒绝会诊邀约通知
  void _onInviteeReject(InviteeRejectApplyConsultationNotification message) {
    final notification = SystemNotification(
      title: i18nBook.notification.sysNotification.t,
      detailTitle: i18nBook.notification.someoneRejectYourInvitation
          .translate(["${message.operatorName ?? ""}"]),
      info: i18nBook.notification.someoneRejectYourInvitation
          .translate(["${message.operatorName ?? ""}"]),
      detailInfos: [
        if (message.rejectReason != null)
          "${i18nBook.notification.rejectReason.t} : ${message.rejectReason!}",
      ],
      payload: Payload(
          type: PayloadType.consultation,
          message: message.consultationCode ?? ""),
    );
    handleReceiveNotification(notification);
  }
}

/// 系统通知
class SystemNotification {
  SystemNotification({
    required this.title,
    required this.info,
    required this.detailTitle,
    required this.detailInfos,
    required this.payload,
  });
  final String title;
  final String info;
  final String detailTitle;
  final List<String> detailInfos;
  final Payload payload;
}
