import 'package:flutter_udid/flutter_udid.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/utils/kr_secure_storage.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'dart:io';
import 'dart:convert';
import 'package:crypto/crypto.dart';

/// 设备工具类
class KRDeviceUtil {
  static final KRDeviceUtil _instance = KRDeviceUtil._internal();
  
  /// 设备ID缓存
  String? _kr_cachedDeviceId;
  
  /// 存储键
  static const String _kr_deviceIdKey = 'kr_device_id';
  
  /// 存储实例
  final KRSecureStorage _kr_storage = KRSecureStorage();

  KRDeviceUtil._internal(); 

  factory KRDeviceUtil() => _instance;

  /// 获取设备ID
  /// 如果获取失败，返回空字符串
  Future<String> kr_getDeviceId() async {
 
    try {
      if (_kr_cachedDeviceId != null) {
        return _kr_cachedDeviceId!;
      }

      // 先从存储中获取
      final String? kr_savedDeviceId = await _kr_storage.kr_readData(key: _kr_deviceIdKey);
      if (kr_savedDeviceId != null) {
        _kr_cachedDeviceId = kr_savedDeviceId;
        return _kr_cachedDeviceId!;
      }

      // 根据不同平台获取设备ID
      if (Platform.isMacOS || Platform.isWindows ) {
        // 获取系统信息
        final PackageInfo kr_packageInfo = await PackageInfo.fromPlatform();
        final String kr_platform = Platform.operatingSystem;
        final String kr_version = Platform.operatingSystemVersion;
        final String kr_localHostname = Platform.localHostname;
        
        // 组合信息生成唯一ID
        final String kr_deviceInfo = '$kr_platform-$kr_version-$kr_localHostname-${kr_packageInfo.packageName}-${kr_packageInfo.buildNumber}';
        _kr_cachedDeviceId = md5.convert(utf8.encode(kr_deviceInfo)).toString();
      } else if (Platform.isIOS || Platform.isAndroid  )  {
       
        _kr_cachedDeviceId = await FlutterUdid.udid;
      } else {
        KRLogUtil.kr_e('不支持的平台: ${Platform.operatingSystem}', tag: 'DeviceUtil');
        return '';
      }

      // 保存到存储中
      if (_kr_cachedDeviceId != null) {
        await _kr_storage.kr_saveData(key: _kr_deviceIdKey, value: _kr_cachedDeviceId!);
      }

      KRLogUtil.kr_i('获取设备ID: $_kr_cachedDeviceId', tag: 'DeviceUtil');
      return _kr_cachedDeviceId ?? '';
    } catch (e) {
      KRLogUtil.kr_e('获取设备ID失败: $e', tag: 'DeviceUtil');
      return '';
    }
  }

  /// 清除缓存的设备ID
  void kr_clearDeviceId() {
    _kr_cachedDeviceId = null;
    _kr_storage.kr_deleteData(key: _kr_deviceIdKey);
  }
} 