import 'package:get/get.dart'; import 'package:get_storage/get_storage.dart'; import 'package:ln_jq_app/common/model/vehicle_info.dart'; /// 定义登录渠道的枚举类型 enum LoginChannel { station, // 站点 driver, // 司机 none, // 未登录或未知 } class StorageService extends GetxService { late final GetStorage _box; // --- 定义存储时使用的键名 (Key) --- static const String _tokenKey = 'user_token'; static const String _userIdKey = 'user_id'; static const String _channelKey = 'login_channel'; static const String _nameKey = 'user_name'; static const String _phoneKey = 'user_phone'; static const String _idCardKey = 'user_id_card'; static const String _vehicleInfoKey = 'vehicle_info'; // 加氢站登录凭证的键名 static const String _stationAccountKey = 'station_account'; static const String _stationPasswordKey = 'station_password'; static StorageService get to => Get.find(); Future init() async { _box = GetStorage(); return this; } // --- Getters --- bool get isLoggedIn => _box.read(_tokenKey)?.isNotEmpty ?? false; String? get token => _box.read(_tokenKey); String? get userId => _box.read(_userIdKey); String? get name => _box.read(_nameKey); String? get phone => _box.read(_phoneKey); String? get idCard => _box.read(_idCardKey); bool get hasVehicleInfo => _box.hasData(_vehicleInfoKey); // 记住密码:获取加氢站账号和密码 String? get stationAccount => _box.read(_stationAccountKey); String? get stationPassword => _box.read(_stationPasswordKey); VehicleInfo? get vehicleInfo { final vehicleJson = _box.read(_vehicleInfoKey); if (vehicleJson != null) { return vehicleInfoFromJson(vehicleJson); } return null; } LoginChannel get loginChannel { final channelString = _box.read(_channelKey); if (channelString == 'station') { return LoginChannel.station; } else if (channelString == 'driver') { return LoginChannel.driver; } return LoginChannel.none; } // --- Methods --- Future saveLoginInfo({ required String token, required String userId, required String channel, String? name, String? phone, String? idCard, }) async { await _box.write(_tokenKey, token); await _box.write(_userIdKey, userId); await _box.write(_channelKey, channel); await _box.write(_nameKey, name); await _box.write(_phoneKey, phone); await _box.write(_idCardKey, idCard); } Future saveVehicleInfo(VehicleInfo data) async { await _box.write(_vehicleInfoKey, vehicleInfoToJson(data)); } // 保存加氢站登录凭证 Future saveStationCredentials(String account, String password) async { await _box.write(_stationAccountKey, account); await _box.write(_stationPasswordKey, password); } Future clearVehicleInfo() async { await _box.remove(_vehicleInfoKey); } // 清除加氢站登录凭证 Future clearStationCredentials() async { await _box.remove(_stationAccountKey); await _box.remove(_stationPasswordKey); } Future clearLoginInfo() async { await _box.remove(_tokenKey); await _box.remove(_userIdKey); await _box.remove(_channelKey); await _box.remove(_nameKey); await _box.remove(_phoneKey); await _box.remove(_idCardKey); await clearVehicleInfo(); // 注意:登出时我们不清除“记住的密码”,以便下次用户登录时仍然可以回填 } }