import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:smart_hotel_app/models/bo/user_info_bo.dart';

class StorageService {
  static const String _keyToken = 'auth_token';
  static const String _keyTokenExpiry = 'auth_token_expiry';
  static const String _keyRememberUsername = 'remember_username';
  static const String _keyRememberPassword = 'remember_password';
  static const String _keyRememberEnabled = 'remember_enabled';
  static const String _keyUserInfo = 'user_info';
  static const String _keyClientId = 'client_id';

  final FlutterSecureStorage _storage = const FlutterSecureStorage(
    aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
    ),
  );

  // ==================== Token 相关 ====================

  Future<void> saveToken(String token, {int expiryHours = 24}) async {
    await _storage.write(key: _keyToken, value: token);
    final expiryTime =
        DateTime.now().add(Duration(hours: expiryHours)).millisecondsSinceEpoch;
    await _storage.write(key: _keyTokenExpiry, value: expiryTime.toString());
  }

  Future<String?> getToken() async {
    return await _storage.read(key: _keyToken);
  }

  Future<int?> getTokenExpiry() async {
    final value = await _storage.read(key: _keyTokenExpiry);
    if (value == null) return null;
    return int.tryParse(value);
  }

  Future<bool> isTokenExpired() async {
    final expiry = await getTokenExpiry();
    if (expiry == null) return false;
    return DateTime.now().millisecondsSinceEpoch > expiry;
  }

  Future<void> deleteToken() async {
    await _storage.delete(key: _keyToken);
    await _storage.delete(key: _keyTokenExpiry);
  }

  Future<bool> hasToken() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  // ==================== 用户信息相关 ====================

  Future<void> saveUserInfo(UserInfoBO userInfo) async {
    final jsonStr =
        '${userInfo.userId}|${userInfo.userName}|${userInfo.nickName}|${userInfo.phonenumber}|${userInfo.email}|${userInfo.sex}|${userInfo.avatarUrl}|${userInfo.deptName}|${userInfo.tenantId}';
    await _storage.write(key: _keyUserInfo, value: jsonStr);
  }

  Future<UserInfoBO?> getUserInfo() async {
    final value = await _storage.read(key: _keyUserInfo);
    if (value == null || value.isEmpty) return null;
    final parts = value.split('|');
    if (parts.length < 9) return null;
    return UserInfoBO(
      userId: int.tryParse(parts[0]) ?? 0,
      userName: parts[1],
      nickName: parts[2],
      phonenumber: parts[3],
      email: parts[4],
      sex: parts[5],
      avatarUrl: parts[6],
      deptName: parts[7],
      tenantId: parts[8],
    );
  }

  Future<void> deleteUserInfo() async {
    await _storage.delete(key: _keyUserInfo);
  }

  // ==================== ClientId 相关 ====================

  Future<void> saveClientId(String clientId) async {
    await _storage.write(key: _keyClientId, value: clientId);
  }

  Future<String?> getClientId() async {
    return await _storage.read(key: _keyClientId);
  }

  Future<void> deleteClientId() async {
    await _storage.delete(key: _keyClientId);
  }

  // ==================== 记住密码相关 ====================

  Future<void> saveRememberCredentials({
    required String username,
    required String password,
  }) async {
    await _storage.write(key: _keyRememberUsername, value: username);
    await _storage.write(key: _keyRememberPassword, value: password);
    await _storage.write(key: _keyRememberEnabled, value: 'true');
  }

  Future<Map<String, String?>> getRememberCredentials() async {
    final enabled = await _storage.read(key: _keyRememberEnabled);
    if (enabled != 'true') {
      return {'username': null, 'password': null};
    }
    final username = await _storage.read(key: _keyRememberUsername);
    final password = await _storage.read(key: _keyRememberPassword);
    return {'username': username, 'password': password};
  }

  Future<void> clearRememberCredentials() async {
    await _storage.delete(key: _keyRememberUsername);
    await _storage.delete(key: _keyRememberPassword);
    await _storage.delete(key: _keyRememberEnabled);
  }

  // ==================== 清空所有数据 ====================

  Future<void> clearAll() async {
    await _storage.deleteAll();
  }
}