import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class DeviceInfo {
  static PackageInfo ? pInfo;
  static String platform = Platform.isAndroid == true ? "ANDROID" : "IOS";
  static String _identifier = '';
  static String _device = '';
  static getDeviceInfo() async {
    pInfo = await PackageInfo.fromPlatform();
    platform = Platform.isAndroid == true ? "ANDROID" : "IOS";
    _device = (await PlatformDeviceId.getDeviceInfo) ?? "";
    await _deviceId();
  }

  static String deviceId() {
    return _identifier;
  }

  static String deviceInfo() {
    return _device;
  }

  static _deviceId() async {
    if (_identifier.isNotEmpty) {
      return;
    }
    var storage = const FlutterSecureStorage(
      aOptions: AndroidOptions(
        encryptedSharedPreferences: true,
        resetOnError: true,
      ),
    );

    _identifier = (await storage.read(key: "deviceIdentifier")) ?? '';
    if (_identifier.isEmpty) {
      _identifier = (await PlatformDeviceId.getDeviceId) ?? '';
      if (_identifier.isNotEmpty) {
        print('=====================  创建id   $_identifier');
        await storage.write(key: "deviceIdentifier", value: _identifier);
      }
    } else {
      print('=====================  手机自身id   $_identifier');
    }
  }
}

/// Provides device id information.
class PlatformDeviceId {
  /// Provides device and operating system information.
  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

  /// Information derived from `android`-`androidId` or `ios`-`identifierForVendor`
  static Future<String> get getDeviceId async {
    String deviceId = "";
    try {
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        deviceId = androidInfo.androidId;
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
        deviceId = iosInfo.identifierForVendor;
      }
    } on PlatformException {
      deviceId = '';
    }
    return deviceId;
  }

  static Future<String> get getDeviceInfo async {
    String getDeviceInfo = "";
    try {
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        getDeviceInfo = androidInfo.model;
        print(androidInfo.model);
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
        getDeviceInfo = iosInfo.name;
      }
    } on PlatformException {
      getDeviceInfo = '';
    }
    return getDeviceInfo;
  }
}
