import 'package:flutter/services.dart';

/// 从原生宿主 App（Android/iOS）获取 ERP 连接配置。
///
/// 对应 Android 端 [HeaderInterceptor] + [WebApiUrl] 的值来源：
/// - baseUrl: Pub_CompInfo.getWebApiUrl()
/// - sn: SharedPreferences "MemberNo"
/// - loginId: SharedPreferences "LoginId"
///
/// iOS 调用示例：
/// ```objc
/// FlutterMethodChannel *ch = [FlutterMethodChannel
///     methodChannelWithName:@"com.tboss.oa/config"
///            binaryMessenger:engine.binaryMessenger];
/// [ch setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
///     result(@"ok"); // 或返回具体值
/// }];
/// ```
class HostAppChannel {
  static const _channel = MethodChannel('com.tboss.oa/config');

  static String? _baseUrl;
  static String? _sn;
  static String? _loginId;

  static String get baseUrl => _baseUrl ?? '';
  static String get sn => _sn ?? '';
  static String get loginId => _loginId ?? '';

  static bool _initialized = false;
  static bool get isInitialized => _initialized;

  /// 从宿主 App 加载配置，需在 runApp 之前调用。
  static Future<void> initialize() async {
    if (_initialized) return;
    try {
      final result = await _channel.invokeMethod<Map<dynamic, dynamic>>('getConfig');
      if (result != null) {
        _baseUrl = result['baseUrl'] as String?;
        _sn = result['sn'] as String?;
        _loginId = result['loginId'] as String?;
      }
    } catch (_) {
      // 调试 / Mock 模式回退
      _baseUrl = 'https://your-api-host.com/api';
      _sn = '';
      _loginId = '';
    }
    _initialized = true;
  }
}
