import 'dart:convert';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:pointycastle/asymmetric/api.dart' show RSAPublicKey;
import 'package:qhd_prevention/tools/tools.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../http/ApiService.dart';

class AuthService {
  static const _keyUser = 'USER';
  static const _keyRemember = 'remember';
  static const _keyIsLoggedIn = 'isLoggedIn';

  /// 登录
  static Future<bool> login(String username, String password) async {
    final parser = encrypt.RSAKeyParser();
    final pub = parser.parse(ApiService.publicKey) as RSAPublicKey;
    final encrypter = encrypt.Encrypter(encrypt.RSA(publicKey: pub));

    final plain = 'zcloudchina$username,zy,$password';

    String encrypted;
    try {
      encrypted = encrypter.encrypt(plain).base64;
    } catch (e) {
      Fluttertoast.showToast(msg: '加密失败：$e');
      return false;
    }

    final data = await ApiService.loginCheck(encrypted);
    final result = data['result'] as String? ?? '';
    if (result != 'success') {
      Fluttertoast.showToast(msg: data['msg'] ?? '');

      return false;
    }

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_keyUser, json.encode(data));
    await prefs.setStringList(_keyRemember, [username, password]);
    await prefs.setBool(_keyIsLoggedIn, true);

    SessionService.instance
      ..setLoginUserId(data['USER_ID'] as String)
      ..setCorpinfoId(data['CORPINFO_ID'] as String)
      ..setDeptId(data['DEPARTMENT_ID'] as String)
      ..setDeptLevel(data['DEPARTMENT_LEVEL'] as String)
      ..setIsRest(data['ISREST'] as String)
      ..setUsername(data['NAME'] as String)
      ..setLoginUser(data);

    return true;
  }
  /// 检查更新
  static Future<Map<String, dynamic>> checkUpdate() async {
    final data = await ApiService.getUpdateInfo();
    final result = data['result'] as String? ?? '';
    if (result == 'success') {
      return data;
    }
    return {};
  }


  /// 验证是否已登录（通过重新登录）
  static Future<bool> isLoggedIn() async {
    final prefs = await SharedPreferences.getInstance();
    final isLocalLoggedIn = prefs.getBool(_keyIsLoggedIn) ?? false;
    if (!isLocalLoggedIn) return false;

    final remember = prefs.getStringList(_keyRemember);
    if (remember == null || remember.length < 2) return false;

    final username = remember[0];
    final password = remember[1];

    // 用存储的账号密码重新登录
    final success = await login(username, password);
    if (!success) {
      await logout();
      return false;
    }
    return true;
  }


  /// 获取已保存的用户信息
  static Future<Map<String, dynamic>?> getUser() async {
    final prefs = await SharedPreferences.getInstance();
    final jsonStr = prefs.getString(_keyUser);
    if (jsonStr == null) return null;
    return json.decode(jsonStr);
  }

  /// 登出
  static Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_keyUser);
    await prefs.remove(_keyRemember);
    await prefs.setBool(_keyIsLoggedIn, false);
  }
}
