import 'dart:io';

import 'package:aliyun_push_flutter/aliyun_push_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/styles/theme.dart';
import 'package:ln_jq_app/pages/b_page/base_widgets/view.dart';
import 'package:ln_jq_app/pages/c_page/base_widgets/view.dart';
import 'package:ln_jq_app/pages/c_page/message/view.dart';
import 'package:ln_jq_app/pages/login/view.dart';

import '../../storage_service.dart';

class HomeController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'home';

  HomeController();

  final _aliyunPush = AliyunPushFlutter();

  @override
  void onInit() {
    super.onInit();
    initAliyunPush();
    addPushCallback();
    FlutterNativeSplash.remove();
  }

  // 根据登录状态和登录渠道返回不同的首页
  Widget getHomePage() {
    requestPermission();
    //登录状态跳转
    if (StorageService.to.isLoggedIn) {
      // 如果已登录，再判断是哪个渠道
      if (StorageService.to.loginChannel == LoginChannel.station) {
        return B_BaseWidgetsPage(); // 站点首页
      } else if (StorageService.to.loginChannel == LoginChannel.driver) {
        return BaseWidgetsPage(); // 司机首页
      } else {
        return LoginPage();
      }
    } else {
      // 未登录，直接去登录页
      return LoginPage();
    }
  }

  void requestPermission() async {
    PermissionStatus status = await Permission.notification.status;
    if (status.isGranted) {
      Logger.d("通知权限已开启");
      return;
    }

    if (status.isDenied) {
      // 建议此处增加一个应用内的 Rationale (解释说明) 弹窗
      status = await Permission.notification.request();
    }
    if (status.isGranted) {
      // 授权成功
      Logger.d('通知已开启');
    } else if (status.isPermanentlyDenied) {
      Logger.d('通知权限已被拒绝，请到系统设置中开启');
    } else if (status.isDenied) {
      Logger.d('请授予通知权限，以便接收加氢站通知');
    }
  }

  ///推送相关
  Future<void> initAliyunPush() async {
    // 1. 配置分离：建议将 Key 提取到外部或配置文件中
    final String appKey = Platform.isIOS ? AppTheme.ios_key : AppTheme.android_key;
    final String appSecret = Platform.isIOS
        ? AppTheme.ios_appsecret
        : AppTheme.android_appsecret;

    try {
      //  初始化推送
      final result = await _aliyunPush.initPush(appKey: appKey, appSecret: appSecret);

      if (result['code'] != kAliyunPushSuccessCode) {
        Logger.d('初始化推送失败: ${result['code']} - ${result['errorMsg']}');
        return;
      }

      Logger.d('阿里云推送初始化成功');
      // 分平台配置
      if (Platform.isIOS) {
        await _setupIOSConfig();
      } else if (Platform.isAndroid) {
        await _setupAndroidConfig();
      }
    } catch (e) {
      Logger.d('初始化过程中发生异常: $e');
    }
  }

  /// iOS 专属配置
  Future<void> _setupIOSConfig() async {
    final res = await _aliyunPush.showIOSNoticeWhenForeground(true);
    if (res['code'] == kAliyunPushSuccessCode) {
      Logger.d('iOS 前台通知展示已开启');
    } else {
      Logger.d('iOS 前台通知开启失败: ${res['errorMsg']}');
    }
  }

  /// Android 专属配置
  Future<void> _setupAndroidConfig() async {
    await _aliyunPush.setNotificationInGroup(true);
    final res = await _aliyunPush.createAndroidChannel(
      "xll_push_android",
      '新消息通知',
      4,
      '用于接收加氢站实时状态提醒',
    );
    if (res['code'] == kAliyunPushSuccessCode) {
      Logger.d('Android 通知通道创建成功');
    } else {
      Logger.d('Android 通道创建失败: ${res['code']} - ${res['errorMsg']}');
    }
  }

  void addPushCallback() {
    _aliyunPush.addMessageReceiver(
      onNotification: _onNotification,
      onNotificationOpened: _onNotificationOpened,
      onNotificationRemoved: _onNotificationRemoved,
      onMessage: _onMessage,
      onAndroidNotificationReceivedInApp: _onAndroidNotificationReceivedInApp,
      onAndroidNotificationClickedWithNoAction: _onAndroidNotificationClickedWithNoAction,
      onIOSChannelOpened: _onIOSChannelOpened,
      onIOSRegisterDeviceTokenSuccess: _onIOSRegisterDeviceTokenSuccess,
      onIOSRegisterDeviceTokenFailed: _onIOSRegisterDeviceTokenFailed,
    );
  }

  Future<void> _onAndroidNotificationClickedWithNoAction(
    Map<dynamic, dynamic> message,
  ) async {
    Logger.d('onAndroidNotificationClickedWithNoAction ====> $message');
  }

  Future<void> _onAndroidNotificationReceivedInApp(Map<dynamic, dynamic> message) async {
    Logger.d('onAndroidNotificationReceivedInApp ====> $message');
  }

  Future<void> _onMessage(Map<dynamic, dynamic> message) async {
    Logger.d('onMessage ====> $message');
  }

  Future<void> _onNotification(Map<dynamic, dynamic> message) async {
    Logger.d('onNotification ====> $message');
  }

  Future<void> _onNotificationOpened(Map<dynamic, dynamic> message) async {
    Logger.d('onNotificationOpened ====> $message');
    await Get.to(() => const MessagePage());
  }

  Future<void> _onNotificationRemoved(Map<dynamic, dynamic> message) async {
    Logger.d('onNotificationRemoved ====> $message');
  }

  Future<void> _onIOSChannelOpened(Map<dynamic, dynamic> message) async {
    Logger.d('onIOSChannelOpened ====> $message');
  }

  Future<void> _onIOSRegisterDeviceTokenSuccess(Map<dynamic, dynamic> message) async {
    Logger.d('onIOSRegisterDeviceTokenSuccess ====> $message');
  }

  Future<void> _onIOSRegisterDeviceTokenFailed(Map<dynamic, dynamic> message) async {
    Logger.d('onIOSRegisterDeviceTokenFailed====> $message');
  }
}
