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? _dep;
  static String? _depName;
  static String? _usr;
  static String? _usrName;

  static String get baseUrl => _baseUrl ?? '';
  static String get sn => _sn ?? '';
  static String get loginId => _loginId ?? '';
  static String get dep => _dep ?? '';
  static String get depName => _depName ?? '';
  static String get usr => _usr ?? '';
  static String get usrName => _usrName ?? '';

  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?;
        _dep = result['dep'] as String?;
        _depName = result['depName'] as String?;
        _usr = result['usr'] as String?;
        _usrName = result['usrName'] as String?;
      }
    } catch (_) {
      // 调试 / Mock 模式回退
      _baseUrl = 'https://your-api-host.com/api';
      _sn = '';
      _loginId = '';
      _dep = '';
      _depName = '';
      _usr = '';
      _usrName = '';
    }
    _initialized = true;
  }

  /// 重新从宿主 App 拉取配置（用于用户切换后刷新）。
  static Future<void> refresh() async {
    try {
      final result = await _channel.invokeMethod<Map<dynamic, dynamic>>('getConfig');
      if (result != null) {
        _baseUrl = result['baseUrl'] as String? ?? _baseUrl;
        _sn = result['sn'] as String? ?? _sn;
        _loginId = result['loginId'] as String? ?? _loginId;
        _dep = result['dep'] as String? ?? _dep;
        _depName = result['depName'] as String? ?? _depName;
        _usr = result['usr'] as String? ?? _usr;
        _usrName = result['usrName'] as String? ?? _usrName;
      }
    } catch (_) {
      // 刷新失败保留旧值
    }
  }
}
