import 'package:fis_ui/values.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/usual/alert.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/lab/env/env.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:universal_html/js.dart' as js;
import 'package:fis_common/index.dart';

/// 账号被挤出通知
class TokenReplacedNotificationHandler
    extends NotificationHandler<TokenReplacedNotification> {
  TokenReplacedNotificationHandler()
      : super(NotificationTypeEnum.TokenReplacedNotification);

  @override
  void execute(TokenReplacedNotification message) {
    super.execute(message);

    if (kIsWeb) {
      // 关闭其他标签页
      js.context.callMethod("closeOtherTabs");
    }

    if (Get.context == null) return;
    try {
      Get.find<FWebviewInteractiveController>().onDialogCreate();
    } catch (e) {
      print(e);
    }
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.auth.tokenReplacedTips.t,
      isShowCancel: false,
      businessParent: FVirtualPageWidget.global,
      cancelLabel: i18nBook.common.cancel.t,
      confrimLabel: i18nBook.common.confirm.t,
      onConfirm: () async {
        if (kIsLab) {
          try {
            await Store.user.handelLogOut();
          } catch (e) {}
          Get.offNamed(RouteNames.Lab.Login);
          return;
        }
        try {
          if ((FPlatform.isWindows || FPlatform.isMacOS) &&
              LocalSetting.ins.isUseSecondWindow!) {
            rpc.platform.tokenExpired();
          }
          Get.find<FWebviewInteractiveController>().onDialogDispose();
        } catch (e) {
          print(e);
        }
        // 重新登录
        await Store.user.handelLogOut();
        Store.app.cancelBusy();

        /// 如果当前是横屏，切换到竖屏
        if (kIsMobile && Get.context!.isLandscape) {
          SystemChrome.setPreferredOrientations(
              [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
          // 延迟1000ms，等待屏幕旋转完成
          await Future.delayed(Duration(milliseconds: 300));
          router.offAll(RouteNames.Auth.AuthBoard);
        } else {
          router.offAll(RouteNames.Auth.AuthBoard);
        }
      },
    );
  }
}
