import 'package:aliyun_push_flutter/aliyun_push_flutter.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:getx_scaffold/common/utils/log_util.dart';
import 'package:ln_jq_app/common/model/vehicle_info.dart';
import 'package:shared_preferences/shared_preferences.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 const String _bindDialogShownKey = 'bind_vehicle_dialog_shown';

  static const String _hostUrlKey = 'host_url';

  // 隐私政策相关
  static const String _privacyAgreedKey = 'privacy_agreed';

  static StorageService get to => Get.find();

  Future<StorageService> init() async {
    _box = GetStorage();
    return this;
  }

  // --- Getters ---
  String? get hostUrl => _box.read<String?>(_hostUrlKey);

  ///：保存自定义域名
  Future<void> saveHostUrl(String url) async {
    await _box.write(_hostUrlKey, url);
  }

  bool get isLoggedIn => _box.read<String?>(_tokenKey)?.isNotEmpty ?? false;

  String? get token => _box.read<String?>(_tokenKey);

  String? get userId => _box.read<String?>(_userIdKey);

  String? get name => _box.read<String?>(_nameKey);

  String? get phone => _box.read<String?>(_phoneKey);

  String? get idCard => _box.read<String?>(_idCardKey);

  bool get hasVehicleInfo => _box.hasData(_vehicleInfoKey);

  String? get stationAccount => _box.read<String?>(_stationAccountKey);

  String? get stationPassword => _box.read<String?>(_stationPasswordKey);

  // 新增：获取”绑定车辆”弹窗是否已显示的标志
  bool get hasShownBindVehicleDialog => _box.read<bool>(_bindDialogShownKey) ?? false;

  // 获取隐私政策是否已同意
  bool get isPrivacyAgreed => _box.read<bool>(_privacyAgreedKey) ?? false;

  VehicleInfo? get vehicleInfo {
    final vehicleJson = _box.read<String?>(_vehicleInfoKey);
    if (vehicleJson != null) {
      return vehicleInfoFromJson(vehicleJson);
    }
    return null;
  }

  LoginChannel get loginChannel {
    final channelString = _box.read<String?>(_channelKey);
    if (channelString == 'station') {
      return LoginChannel.station;
    } else if (channelString == 'driver') {
      return LoginChannel.driver;
    }
    return LoginChannel.none;
  }

  // --- Methods ---
  Future<void> 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);

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', token);
  }

  Future<void> saveVehicleInfo(VehicleInfo data) async {
    await _box.write(_vehicleInfoKey, vehicleInfoToJson(data));

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('plateNumber', data.plateNumber);
  }

  Future<void> saveStationCredentials(String account, String password) async {
    await _box.write(_stationAccountKey, account);
    await _box.write(_stationPasswordKey, password);
  }

  // 保存隐私政策同意状态
  Future<void> savePrivacyAgreed(bool agreed) async {
    await _box.write(_privacyAgreedKey, agreed);
  }

  // 新增：标记“绑定车辆”弹窗已显示
  Future<void> markBindVehicleDialogAsShown() async {
    await _box.write(_bindDialogShownKey, true);
  }

  Future<void> clearVehicleInfo() async {
    await _box.remove(_vehicleInfoKey);

    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('plateNumber');
    await prefs.remove('token');
  }

  Future<void> clearStationCredentials() async {
    await _box.remove(_stationAccountKey);
    await _box.remove(_stationPasswordKey);
  }

  Future<void> 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();
    // 登出时，清除“绑定车辆”弹窗的显示记录，以便下次登录时可以再次弹出
    await _box.remove(_bindDialogShownKey);

    delAlias();
  }

  final _aliyunPush = AliyunPushFlutter();

  void delAlias() async {
    String phoen = StorageService.to.phone ?? "";
    var result = await await _aliyunPush.unbindAccount();
    var code = result['code'];
    if (code == kAliyunPushSuccessCode) {
      Logger.d('删除别名$phoen成功');
    } else {
      var errorCode = result['code'];
      var errorMsg = result['errorMsg'];
      Logger.d('删除别名$phoen失败: $errorCode - $errorMsg');
    }
  }
}
